为什么非成员函数不能用于重载赋值运算符? [英] Why cannot a non-member function be used for overloading the assignment operator?

查看:33
本文介绍了为什么非成员函数不能用于重载赋值运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

赋值运算符可以使用成员函数重载,但不能使用非成员friend函数:

The assignment operator can be overloaded using a member function but not a non-member friend function:

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 =' 必须是非静态成员

error C2801: 'operator =' must be a non-static member

为什么不能使用 friend 函数来重载赋值运算符?编译器允许使用 friend 重载其他运算符,例如 +=-=.支持 operator= 的固有问题/限制是什么?

Why cannot a friend function be used for overloading the assignment operator? The compiler is allowing to overload other operators such as += and -= using friend. What's the inherent problem/limitation in supporting operator=?

推荐答案

因为编译器提供的默认 operator=(成员副本)将始终优先.IE.你的朋友 operator= 永远不会被调用.

Because the default operator= provided by the compiler (the memberwise copy one) would always take precedence. I.e. your friend operator= would never be called.

这个答案正在回答

支持 = 运算符的固有问题/限制是什么?

Whats the inherent problem/limitation in supporting = operator ?

问题的一部分.这里的其他答案引用了标准中说你不能这样做的部分,但这很可能是为什么标准的那部分是这样编写的.

portion of the question. The other answers here quote the portion of the standard that says you can't do it, but this is most likely why that portion of the standard was written that way.

这篇关于为什么非成员函数不能用于重载赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆