赋值运算符可以使用成员函数重载,但不能使用非成员friend函数重载:
class Test
{
int a;
public:
Test(int x)
:a(x)
{}
friend Test& operator=(Test &obj1, Test &obj2);
};
Test& operator=(Test &obj1, Test &obj2)//Not implemented fully. just for test.
{
return obj1;
}
Run Code Online (Sandbox Code Playgroud)
它会导致此错误:
错误C2801:'operator ='必须是非静态成员
为什么friend函数不能用于重载赋值运算符?编译器允许重载其他运算符,例如+=和-=使用friend.支持的固有问题/限制是operator=什么?