赋值运算符可以使用成员函数重载,但不能使用非成员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=什么?
C++中有4个运算符可以重载但不能作为独立(即非成员,独立)函数重载.这些运营商是:
operator = operator ()operator ->operator []这个主题完全解释了禁止operator =成为非成员函数的理由.关于其他三个的任何想法?