开发者

C++ Operator Overload - call function to get value inside overload

开发者 https://www.devze.com 2023-04-02 17:45 出处:网络
Is there a way I can call an operator overload in C++开发者_运维知识库 and call the parameter\'s function during the comparison?

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!


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:

  • http://www.parashift.com/c++-faq-lite/const-correctness.html
  • http://www.gotw.ca/gotw/006.htm
  • http://www.possibility.com/Cpp/const.html

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


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.


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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号