我想在课外使用运算符重载。我在文档中读到,当我们在类之外使用它时,我们可以给出两个对象作为参数。当我使用范围解析运算符在类外定义它时,它给了我错误。我想知道原因
class Rectangle
{
public:
int L;
int B;
Rectangle() //default constructor
{
L = 2;
B = 2;
}
Rectangle(int l,int b) //parametrized constructor
{
L = l;
B = b;
}
void Display()
{
cout<< "length is " << L <<endl;
cout<< "breadth is " << B <<endl;
}
};
Rectangle Rectangle:: operator+ (Rectangle obj1,Rectangle obj2)
{
Rectangle obj3;
obj3.L = obj1.L + obj2.L;
obj3.B = obj1.B + obj2.B;
return obj3;
}
int main()
{
Rectangle R1;
R1.Display();
Rectangle R2(5,3);
R2.Display();
Rectangle R3 ;
R3 = R1+ R2;
R3.Display();
return 0;
}
答案 0 :(得分:1)
你几乎得到了它。双参数形式实际上是一个自由函数,它将由ADL找到,而不是成员:
Rectangle operator+ (Rectangle obj1,Rectangle obj2)
{
Rectangle obj3;
obj3.L = obj1.L + obj2.L;
obj3.B = obj1.B + obj2.B;
return obj3;
}