gpt4 book ai didi

C++ 使用参数委托(delegate) ctor 和父 ctor

转载 作者:搜寻专家 更新时间:2023-10-30 23:54:04 25 4
gpt4 key购买 nike

这在 C++11 中似乎不起作用:

class B : public A
{
public:
B(const A& a)
: A(a) // parent constructor for passing the parameter
, B() // delegating constructor for init of other members
{};
// ...
};

gcc 告诉我委托(delegate)构造函数的初始化程序必须单独出现

如何既带参调用父类的构造函数,又调用B类的基本构造函数? (我在 B 中有一堆其他构造函数需要相同的行为)。

现在我正在考虑编写一个私有(private) B::init() 函数并在所有构造函数主体中使用它,但这有点像 C++03。

首选解决方案是什么?

最佳答案

我认为委托(delegate)的首选方式是相反的方式,它并不意味着用于重构构造函数的公共(public)部分,而是将更简单的委托(delegate)定义为更复杂情况的特例。

因此您应该从 B(const A& a) 开始并将其用作委托(delegate)目标。

class B : public A
{
public:
B() : B(A());
B(const A& a) : A(a) // parent constructor for passing the parameter
{};
};

你在创建 B 时调用了 A()

其背后的基本原理是,当您有两个“部分专门化”的 c'tor 时,您将无法使用它们来初始化复杂的 c'tor。例如:

class B : public A
{
public:
B() {};
B(int) : B() {};
B(double) : B() {};
B(double,int) : B(int), B(double) {}; // can't do it.
};

我相信 Bathsheba 的回答中解释了技术原因。看看如果你在 B() 中有一个公共(public)部分会发生什么:

class B : public A
{
public:
B() {};
B(int) : B() {};
B(double) : B() {};
B(double,int) : B(int), B(double) {}; //ooops would get B() called twice!
};

这是继承已知的菱形继承(钻石问题)。解决方案是颠倒逻辑。

class B : public A
{
public:
B() : B(0,0) {};
B(int a) : B(a,0) {};
B(double d) : B(0,d) {};
B(double a, int d) {/*full implementation*/};
};

关于C++ 使用参数委托(delegate) ctor 和父 ctor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427897/

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