相关疑难解决方法(0)

为什么不能使用非成员函数来重载赋值运算符?

赋值运算符可以使用成员函数重载,但不能使用非成员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++ operator-overloading assignment-operator

30
推荐指数
4
解决办法
2万
查看次数