gpt4 book ai didi

c++ - 如何将 “= default”与具有主体的构造函数一起使用?

转载 作者:行者123 更新时间:2023-12-02 10:18:06 24 4
gpt4 key购买 nike

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

像这样:

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.
}
};

最佳答案

从构造的 Angular 来看,这没有多大意义,因为构造函数的工作是设置成员数据,仅此而已。

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

class Y : public X
{
Y(const Y&){
// Do some work
}
// No member data here
};

关于c++ - 如何将 “= default”与具有主体的构造函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61265749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com