C++运算符重载 - 调用函数以获取重载内的值
有没有办法可以在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将函数设置为 const,因为您使用的是对 const MyClass 的引用:
您可以在以下位置阅读有关 const 的良好使用(const 正确性)的信息:
此外,我建议您使运算符<而是一个免费函数。
You need to make the functions const, since you are using a reference to const MyClass:
You can read about good use of const (const correctness) at:
Additionally I would recommend that you make the operator< a free function instead.
它不起作用,因为
getX()
不是const
函数。改成:就可以了。您还可以删除运算符参数中的
const
,但这通常不会被认为是好的。It doesn't work because
getX()
is not aconst
function. Change it to:and it will work. You could also remove the
const
in the operator argument, but that wouldn't normally be considered as good.访问是按类进行的,而不是按实例进行的。您可以毫无问题地访问
other.x
。除此之外,您可以返回一个 const 引用,但它实际上不会对性能产生任何影响,而且看起来很奇怪。
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.
您可以将运算符声明为该类的友元。
编辑:我的眼睛里好像有西红柿,您的操作员是班级成员并且已经拥有私人访问权限。您可以将其添加为好友,但它是在类范围之外定义的。
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.