gpt4 book ai didi

c++ - 在 C++ 中,如何在父类的构造函数中测试对象是否是子类的实例?

转载 作者:行者123 更新时间:2023-11-30 03:05:49 25 4
gpt4 key购买 nike

我试图断言如果对象是特定子类类型,则传递给父类构造函数的指针仅为 NULL 使用 动态转换:

#include <iostream>
class Parent {
public:
Parent(void *ptr);
virtual ~Parent(); // to make Parent polymorphic
};

class Child1 : public Parent {
public:
Child1() : Parent(0) { std::cout << "Child1 ctor\n";};
};
class Child2 : public Parent {
public:
Child2() : Parent(0) { std::cout << "Child2 ctor\n";};
};

Parent::Parent(void *ptr) {
if (0 == ptr && 0 == dynamic_cast<Child1*>(this)) {
std::cerr<<"ERROR\n";
}
}
Parent::~Parent() {};

int main(void) {
Child1 *c1 = new Child1();
Child2 *c2 = new Child2();
}

这打印:

ERROR
Child1 ctor
ERROR
Child2 ctor

然而,我希望在 Child2 构造期间看到ERROR

当我在 Child1Parent 构造函数中从 Child1 调用时,为什么 dynamic_cast 返回非 NULL的构造函数初始化列表?另外,是否有不同的方法来完成此测试?

最佳答案

当您在 Parent 构造函数(它是一个基类)中时,Child 尚未构造。因此,在 Parent 的构造函数中,this 的动态类型将始终为 Parent。

关于c++ - 在 C++ 中,如何在父类的构造函数中测试对象是否是子类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7438865/

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