我正在学习 C++,并且正在阅读 C++:The Complete Reference
中的复制构造函数。书上说的
It is permissible for a copy constructor to have additional parameters as long as they have default arguments defined for them. However, in all cases the first parameter must be a reference to the object doing the initializing.
但我很困惑,我们将如何传递这些附加参数?我确信应该有一些方法没有在书中给出而且我无法弄清楚。谁能帮帮我?
编辑: 也可以在所有三种情况下传递这些额外参数,即
- 当一个对象显式初始化另一个对象时,例如在声明中
- 当一个对象的拷贝被传递给一个函数时
- 生成临时对象时(最常见的是作为返回值)
最佳答案
这是一个简单的例子:
class A {
//...
public:
A (const A&, bool deep = false) {
if (!deep) { /* make a shallow copy */ }
else { /* make a deep copy */ }
}
};
void foo (A x) { /*...*/ }
A bar () { /*...*/ return A(); }
A a_var;
在此示例中,参数默认为 false,这意味着默认的复制构造函数将很浅。
A b(a_var); // b gets a shallow copy of a
foo(b); // foo() receives a shallow copy
但是,可以通过在第二个参数中传递 true 来实现深拷贝。
A b(a_var, true); // b gets a deep copy of a
foo(A(b, true)); // foo receives a shallow copy of a deep copy
类似地,对于返回 A
的函数,返回的拷贝会很浅,因为它使用默认值,但接收方在接收到它时可以使其变深。
A b(bar()); // shallow
A b(bar(), true); // deep
请记住,当您定义一个复制构造函数时,很可能意味着您将需要定义一个析构函数并重载赋值运算符(三规则)。
关于c++ - 多参数复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10943491/