如何在具有主体的构造函数中使用“ = default”?

问题描述 投票:1回答:1

假设我有一个包含几个成员变量的类。例如,在复制构造函数中,我想复制所有成员并做更多工作。而不是显式复制成员变量,而是如何告诉编译器具有默认行为(复制成员变量),以及如何执行函数主体中的操作?

类似这样的东西:

class X
{
public:

    // This constructor should copy all the members
    // and also do what's inside the constructor's body.   
    X(const X& x) = default
    {
        // Do some work.
    }
};
c++ constructor default
1个回答
0
投票

从构造角度看,这没有多大意义。

构造函数的工作是设置成员数据,仅此而已。

但是,如果您需要这种模式,例如为了以某种方式注册对象,则将有一个解决方案

class Y : public X
{
    Y(const Y&){
        // Do some work
    }
    // No member data here 
};
© www.soinside.com 2019 - 2024. All rights reserved.