【发布时间】:2011-11-09 11:22:37
【问题描述】:
有没有一种方法可以在 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 公开?有没有办法做到这一点?
感谢您的帮助!
【问题讨论】:
-
很难触及您问题的核心。您发布的代码没有任何问题,
other.getX()和other.x都有效(但getX()需要标记为const)。 -
@Martin:不,它不起作用。查看答案。
-
@RTT:是的,我在先评论后注意到了 const 问题。但是,两个调用都可以,只是不是 const 正确的。有趣的是,有些帖子在一个人能够写几行 cmets 之前得到 4 个答案 :)
-
@RTT:您真的不应该将我的答案标记为已接受...
-
你可以这样做
x < other.x一个类自动成为它自己的朋友。因此,您可以完全访问同一类的其他实例的成员。
标签: c++ function overloading operator-keyword