我想添加兩個對象。當我在運算符重載中傳遞兩個參數時,它給了我一個錯誤,即必須有零個或一個參數。我想知道爲什麼我不能將兩個對象作爲參數傳遞以添加它們。在運算符重載中傳遞參數號時出錯?
class Rectangle
{
private:
int L;
int B;
public:
Rectangle() //default constructor
{
L = 2;
B = 2;
}
Rectangle(int l,int b) //parametrized constructor
{
L = l;
B = b;
}
Rectangle operator+ (Rectangle obj1,Rectangle obj2) //operator overloading
{
Rectangle obj3
obj3.L = obj1.L + obj2.L;
obj3.B = obj1.B + obj2.B;
return obj3
}
void Display()
{
cout<< "length is " << L <<endl;
cout<< "breadth is " << B <<endl;
}
};
int main()
{
Rectangle R1;
R1.Display();
Rectangle R2(5,3);
R2.Display();
//Rectangle R3;
//R3 = R1 + R2;
//R3.Display();
return 0;
}
如果它是一個成員函數,那麼對象本身會有一個自動的額外參數('* this')。 –
在構造函數中使用初始化列表 –
並閱讀有關const引用。對操作符更好並保存複製 –