有没有一种方法可以在 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 公开?有办法吗?
感谢您的帮助!
最佳答案
您需要将函数设为常量,因为您正在使用对 const MyClass 的引用:
int getX() const;
您可以在以下位置阅读有关 const(const 正确性)的良好用法:
- http://www.parashift.com/c++-faq-lite/const-correctness.html
- http://www.gotw.ca/gotw/006.htm
- http://www.possibility.com/Cpp/const.html
此外,我建议您将运算符<改为免费函数。
关于C++ 运算符重载 - 调用函数以获取重载中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7288892/