gpt4 book ai didi

c++ - 调用复制 ctor 和另一个 ctor

转载 作者:行者123 更新时间:2023-11-28 03:33:56 25 4
gpt4 key购买 nike

我在我的代码中定义了一个复制构造函数,它正在初始化正在创建的对象的数据成员。现在,如果我只需要更改几个变量的值,我正在编写一个新的复制构造函数。所以我的问题是,我是否可以只初始化特定的不同数据成员,而不是再次编写相同的代码,而对于其他数据成员,我可以只在我的 ctor 方法中调用定义的一个 ctor。

例子:已经存在

A::A(const A& cpy)
{
a=cpy.a;
b=cpy.b;
c=cpy.c
}

现在我想把我的ctor写成

A::A(const A& cpy, bool x)
{
if( x)
a=something;
else
a =cpy.a
//call first ctor for other variables (b and c)
}

谢谢茹琪

最佳答案

从 C++11 开始你可以这样做:

class A 
{
public:

A(const A& cpy) { a=cpy.a; b=cpy.b; c=cpy.c; }
A(const A& cpy, bool x): A(cpy) { a = something_else; }
}

关于c++ - 调用复制 ctor 和另一个 ctor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11685371/

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