加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 复制具有多个参数的构造函数

发布时间:2020-12-16 03:18:58 所属栏目:百科 来源:网络整理
导读:我正在学习C,正在从C:完整参考中读取复制构造函数.这些书说 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 ref
我正在学习C,正在从C:完整参考中读取复制构造函数.这些书说

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

记住当你定义一个复制构造函数时,很可能意味着你需要定义一个析构函数并重载赋值运算符(三条规则).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读