gpt4 book ai didi

C++ 继承基础构造函数,但仍调用默认的派生构造函数

转载 作者:行者123 更新时间:2023-11-30 02:25:42 26 4
gpt4 key购买 nike

我一直在努力解决这个问题:

目前我有这段代码:

class B {
public:
B(int, int, int, int);
[many other ctors]
};

class D : public B {
public:
using B::B;
[other methode]
};

现在我希望 D 管理一些指针,我需要独立于传递给构造函数的参数对其进行初始化。

我已经试过了:

class B {
public:
B(int, int, int, int) {
[other stuff]
init();
}
[many other ctors]
virtual void init() {}
};

class D : public B {
public:
using B::B;
void init() {
mPointer = new Stuff(42);
}

private:
mPointer = nullptr;
};

但显然,如果您从 B::B(int,int,int,int) 调用虚方法,它会调用 B::init,而不是 D::init。

有没有好的方法来完成这项工作,或者我是否需要在 D 中重写 B 的所有 ctors?

谢谢!

最佳答案

您不能从构造函数中调用虚函数。这与对象的构造顺序有关:

struct E {
E() { std::cout << "E" << std::endl; }
int g = 7;
};

struct F : E {
B() { std::cout << "F" << g << std::endl; }
};

F f;

构造f时,程序会输出EF7。首先构建基类,因此在派生类中可以调用父类的方法和使用成员。

事实上,通过上面的简单例子,你可以在F构造函数中使用变量g,因为之前调用了父构造函数。否则它将是错误的,因为 E 的构造函数是将 g 设置为 7

这与您的问题有什么关系?

好吧,在基本构造函数中,您正在调用一个虚函数。您希望调用的虚函数在派生类中被分派(dispatch)。问题是,还没有派生类。

你看,类 B 是最先构建的。还没有 D 存在!由于 D 还不存在,虚拟调度无法调用 D 函数!因此,编译器将回退到当时可以选择的函数。在您的例子中,该函数是 B 初始化函数。

关于C++ 继承基础构造函数,但仍调用默认的派生构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43894417/

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