【发布时间】:2020-08-15 14:03:51
【问题描述】:
我想问一个关于 C++ 中运算符重载的问题。
我是 C++ 初学者,一直在学习 OOP。
考虑以下重载的复制赋值运算符:
class Base {
private:
int value;
public:
Base () : value {0}
{
cout << "Base No-args constructor" << endl;
}
Base (int x) : value {x} {
cout << "Base (int) overloaded constructor" << endl;
}
Base (const Base &other) : value {other.value} {
cout << "Base copy constructor" << endl;
}
Base & operator = (const Base &rhs) {
cout << "Base operator=" << endl;
if (this == &rhs)
return *this;
value = rhs.value;
return *this;
}
~ Base () {cout << "Base Destructor" << endl;}
};
我想澄清两点。
- 这个复制赋值运算符是如何工作的?
- operator关键字前的引用是否需要参数名?
我想就 (1) 给出我的解释。
如果我的main() 中有以下代码:
Base b {100}; // overloaded constructor
Base b1 {b}; // copy constructor
b = b1; // copy assignment
我认为发生的情况是a1 调用了无参数构造函数,显然是因为没有参数传递到对象的构造中。
当a2 被初始化时,会生成a1 的临时副本,然后根据Base 类评估运算符,因此运行Base 重载复制分配块,并且a1 对象是通过return *this 返回到引用a2。
为了解释我对第二个问题的想法,
我认为声明函数或方法时所有参数都需要一个名称(我当然可能错了)。
如果我的重载复制分配块假设写为:
Base &lhs operator = (const Base &rhs)
我说lhs 指的是a2 是否正确,但是由于隐含的this 参数,我们不对lhs 做任何事情,我们不需要在后面给出参数名称运算符前面的 & 号?
【问题讨论】:
-
Base a2 = a1;是通过复制构造函数初始化a2。它不使用赋值运算符。 -
@Eljay 我更新了代码以更好地适应问题!