必须指定赋值运算符的参数吗? [英] Must parameter of assignment operator be reference?

查看:79
本文介绍了必须指定赋值运算符的参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

这篇关于必须指定赋值运算符的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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