Number of arguments in operator overload in C++

前端 未结 5 1474
梦如初夏
梦如初夏 2021-01-31 04:09

I\'m learning C++ and I created two simple hello-world applications. In both of them I use operator overload, but here is the problem. On the first one, I can provide two argume

5条回答
  •  粉色の甜心
    2021-01-31 05:02

    If overloaded function is a member function to the class, the we pass only one argument, and there is one hidden parameter (this pointer) that points to other object required to perform binary operation like '+'. this pointer points to one of the operands and calls the overloaded function; while other operand is passed as an argument. Example:

    class ExampleClass
    {
    public:
       int x;
       //a this pointer will be passed to this function
       ExampleClass& operator+(const ExampleClass& o){ return x+o.x; }
    };
    
    
    
    ExampleClass obj1, obj2, obj;
    obj = obj1 + obj2; //the overloaded function is called as obj1.operator+(obj2) internally
                      //this pointer is passed to the function
    

    When the overloaded function is not a member function (either a free function or a friend function), then we don't have the this pointer provided to the overloaded function. In this case, the compiler expects two arguments to the function which are used as operands.

    class ExampleClass
    {
        public:
           int x;
           //this pointer will not be passed to this function
           friend ExampleClass& operator+(const ExampleClass& o1, const ExampleClass& o2){ return o1.x+o2.x; }
    };
    
    
    
    obj = obj1 + obj2; //the overloaded function is called as operator+(obj1, obj2) internally
    

提交回复
热议问题