我想知道如何为operator+中的以下语句编写operator=成员函数和main成员。

我不想添加朋友功能。

int main(){
  A obj1, obj2, obj3;

  obj2 = obj1 + 10;

  obj3 = 20 + obj1;

  return 0;

}

//Below is my class

//Please add necessary assignment and additions operator+ functions

class A{

   int i;

 public :

      A(){i = 0;}

     A& operator=(const A &obj){

        i = obj.i;
        return *this;
    }
};

最佳答案

您说您不想使用朋友功能,但是很艰难,那是正确的方法。您不需要自定义分配运算符。隐式构造函数将自动将整数转换为A的实例。这将与main中的代码一起使用。

class A
{
public :
    A(int i = 0) : i(i) {}

    friend A operator + (const A& left, const A& right)
    {
        return A(left.i + right.i);
    }

private:
    int i;
};

关于c++ - 仅具有成员函数的C++重载+运算符,用于添加带有整数的类对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25382172/

10-11 22:38
查看更多