'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?

前端 未结 3 1093
眼角桃花
眼角桃花 2020-11-28 03:25

In a project I\'m working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation

3条回答
  •  孤城傲影
    2020-11-28 03:41

    You're getting compilation errors when operator<< is a member function in the example because you're creating an operator<< that takes a Score as the first parameter (the object the method's being called on), and then giving it an extra parameter at the end.

    When you're calling a binary operator that's declared as a member function, the left side of the expression is the object the method's being called on. e.g. a + b might works like this:

    A a;
    B b
    
    a.operator+(b)
    

    It's typically preferable to use non-member binary operators (and in some cases -- e.g. operator<<for ostream is the only way to do it. In that case, a + b might work like this:

    A a;
    B b
    
    operator+(a, b);
    

    Here's a full example showing both ways of doing it; main() will output '55' three times:

    #include 
    
    struct B
    {
        B(int b) : value(b) {}
        int value;
    };
    
    
    struct A
    {
        A(int a) : value(a) {}
        int value;
    
        int operator+(const B& b) 
        {
            return this->value + b.value;
        }
    };
    
    int operator+(const A& a, const B& b)
    {
        return a.value + b.value;
    }
    
    int main(int argc, char** argv)
    {
        A a(22);
        B b(33);
    
        std::cout << a + b << std::endl;
        std::cout << operator+(a, b) << std::endl;
        std::cout << a.operator+(b) << std::endl;
    
        return 0;
    }
    

提交回复
热议问题