C++运算符重载 - 调用函数以获取重载内的值

发布于 2024-12-02 20:50:39 字数 509 浏览 4 评论 0原文

有没有办法可以在 C++ 中调用运算符重载并在比较期间调用参数的函数?

例如:

class MyClass{
  private:
    int x;
    int y;
  public:
    MyClass(int x, int y);
    int getX();
    int getY();
    bool operator < (const MyClass &other) const {
        return (x < other.getX()); //this does not work!
        // this would work, though, if x was public:
        // return x < other.x;
    }
};

基本上,在我调用 other.getX() 的地方,如何使其通过函数返回自己的 x 值以与本地值进行比较,而不必将 x 公开?有办法做到这一点吗?

感谢您的帮助!

Is there a way I can call an operator overload in C++ and call the parameter's function during the comparison?

For example:

class MyClass{
  private:
    int x;
    int y;
  public:
    MyClass(int x, int y);
    int getX();
    int getY();
    bool operator < (const MyClass &other) const {
        return (x < other.getX()); //this does not work!
        // this would work, though, if x was public:
        // return x < other.x;
    }
};

Basically, where I call other.getX(), how can I make it return its own x-value through a function to compare to the local one, instead of having to make x public? Is there a way of doing that?

Thanks for all your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ζ澈沫 2024-12-09 20:50:39

您需要将函数设置为 const,因为您使用的是对 const MyClass 的引用:

int getX() const;

您可以在以下位置阅读有关 const 的良好使用(const 正确性)的信息:

此外,我建议您使运算符<而是一个免费函数。

You need to make the functions const, since you are using a reference to const MyClass:

int getX() const;

You can read about good use of const (const correctness) at:

Additionally I would recommend that you make the operator< a free function instead.

神仙妹妹 2024-12-09 20:50:39

它不起作用,因为 getX() 不是 const 函数。改成:

int getX() const;

就可以了。您还可以删除运算符参数中的 const,但这通常不会被认为是好的。

It doesn't work because getX() is not a const function. Change it to:

int getX() const;

and it will work. You could also remove the const in the operator argument, but that wouldn't normally be considered as good.

若水般的淡然安静女子 2024-12-09 20:50:39

访问是按类进行的,而不是按实例进行的。您可以毫无问题地访问 other.x

除此之外,您可以返回一个 const 引用,但它实际上不会对性能产生任何影响,而且看起来很奇怪。

bool operator < (const MyClass &other) const
{
    return x < other.x;
}

Access is per-class, not per-instance. You can access other.x with no problem.

Other than that, you could return a const reference, but it really wouldn't make any difference performance-wise and just looks weird.

bool operator < (const MyClass &other) const
{
    return x < other.x;
}
欢你一世 2024-12-09 20:50:39

您可以将运算符声明为该类的友元。

编辑:我的眼睛里好像有西红柿,您的操作员是班级成员并且已经拥有私人访问权限。您可以将其添加为好友,但它是在类范围之外定义的。

You can declare the operator as a friend of the class.

Edit: I seem to have tomatoes on my eyes, your operator is class member and already has private access. You could friend it however it was defined outside of class scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文