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

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

问题描述

赋值运算符可以使用成员函数而不是非成员函数重载:

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

a friend 函数用于重载赋值运算符?编译器允许重载其他操作符,例如 + = - = / code>。支持 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 = (成员拷贝)将始终优先。也就是说你的朋友 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天全站免登陆