赋值运算符可以使用成员函数进行重载,但不能使用非成员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;
}
这导致了以下错误:
错误 C2801:'operator='必须是非静态成员
为什么不能使用friend
函数来重载赋值运算符?编译器允许使用friend
来重载其他运算符,如+=
和-=
。支持operator=
的内在问题/限制是什么?
operator =
的定义)的移动可能会完全改变周围代码的语义。如果某个代码片段在定义之前,现在又恰好在定义之后,那么它的语义将会发生变化,因为它将自动从编译器提供的operator =
切换到用户定义的operator =
。 - AnT stands with Russia