问题描述
在C ++中重载类的赋值运算符时,其参数是否必须为引用?
When overloading assignment operator of a class in C++, must its parameter be reference?
例如,
class MyClass {
public:
...
MyClass & operator=(const MyClass &rhs);
...
}
可以
class MyClass {
public:
...
MyClass & operator=(const MyClass rhs);
...
}
?
谢谢!
推荐答案
重载的赋值运算符的参数可以是任何类型,并且可以按引用或按值传递(当然,如果该类型不可复制构造,则显然,它不能通过值传递.
The parameter of an overloaded assignment operator can be any type and it can be passed by reference or by value (well, if the type is not copy constructible, then it can't be passed by value, obviously).
因此,例如,您可以有一个赋值运算符,该赋值运算符将 int
作为参数:
So, for example, you could have an assignment operator that takes an int
as a parameter:
MyClass& operator=(int);
副本分配运算符是分配运算符的特例.任何赋值运算符都可以通过值或引用采用与类相同的类型(引用可以是const或volatile限定的).
The copy assignment operator is a special case of an assignment operator. It is any assignment operator that takes the same type as the class, either by value or by reference (the reference may be const- or volatile-qualified).
如果您未显式实现某种形式的副本分配运算符,则编译器将隐式声明并实现一个形式.
If you do not explicitly implement some form of the copy assignment operator, then one is implicitly declared and implemented by the compiler.
这篇关于必须指定赋值运算符的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!