0 c++ overloading function operator-keyword
有没有办法可以在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;
}
};
Run Code Online (Sandbox Code Playgroud)
基本上,在我调用other.getX()的地方,如何让它通过一个函数返回自己的x值,以便与本地函数进行比较,而不是让x公共?有没有办法做到这一点?
感谢你的帮助!
您需要使函数为const,因为您正在使用对const MyClass的引用:
int getX() const;
Run Code Online (Sandbox Code Playgroud)
您可以在以下位置阅读有关const(const correctness)的使用情况:
另外我建议你让操作员<自由功能.
它不起作用,因为getX()它不是一个const功能.将其更改为:
int getX() const;
Run Code Online (Sandbox Code Playgroud)
它会起作用.您也可以删除const运算符参数中的内容,但这通常不会被认为是好的.