重载赋值运算符
我们可以将赋值运算符重载为普通函数,但不能将赋值运算符重载为友元函数。为什么?
We can overload assignment operator as a normal function, but we cannot overload assignment operator as a friend function. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为 C++ 标准如此规定,第 13.5.3/1 条:
这就是您真正需要知道的全部。友元函数不是成员函数,因此不能用于重载赋值运算符。
Because the C++ Standard says so, Article 13.5.3/1:
That's all you really need to know. A friend function is not a member function, so it cannot be used to overload the assignment operator.
如果你想写:
MyClassObject = MyFriendObject;
然后,您需要实现一个构造函数,它将对友元类的 const 引用作为参数。
If you would like to write:
MyClassObject = MyFriendObject;
Then you would want to implement a constructor that takes a const reference to the friend class as it's parameter.
友元函数重载和成员函数重载的区别在于,调用对象必须是成员函数重载中的第一个操作数,而友元函数重载没有限制。这就是该标准背后的原因。同样,其他一些需要第一个操作数作为调用函数的运算符必须使用成员函数进行重载(例如:
=、[]、->、
和( )
) 。The difference between overloading by friend function and overloading by member function is that the calling object must be the first operand in overloading by member function, while there is no restriction in overloading by friend function. This is the reason behind the standard. Similarly, some other operators requiring the first operand to be the calling function must be overloaded using member functions (examples:
=, [], ->,
and( )
).您不能在类之外使用“自由函数”“扩展”赋值运算符,但您可以设计类以使其允许这样做:
Data.h
Point.h
Assignment.h
You cannot "extend" the assignment operator with a "free function" outside the class, but you can design the class so it will allow it:
Data.h
Point.h
Assignment.h