我想知道如何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++ 重载 + 运算符只有成员函数用于添加带有整数的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382172/