gpt4 book ai didi

c++ - 覆盖在祖 parent 的构造函数中调用的祖 parent 的虚拟方法

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:49 24 4
gpt4 key购买 nike

我的 C++ 代码有问题..

class GrandParent {
public:
GrandParent()
{
printMe();
}

virtual void printMe()
{
std::cout << "GrandParent: printme" << std::endl;
}
}

class Parent : public GrandParent {
public:
Parent(){}
virtual void printMe()
{
std::cout << "Parent: printMe!" << std::endl;
}
}

class Child : public Parent {
public:
Child(){}

void printMe()
{
std::cout << "Child: printMe!" << std::endl;
}
}

int main()
{
Child *p = new Child();
delete p;
}

当我运行这段代码时,它会打印“GrandParent: printMe”。我的目标是打印“Child: printMe!”。重写 printMe 有什么问题吗?

最佳答案

您尝试执行的操作是不可能的。在 GrandParent 的构造函数中,Child 对象唯一被构造和初始化的部分是 GrandParent 部分——包括虚表。也就是说,当您调用 printMe() 时,条目将是 GrandParent 的。只有在构造 Child 之后,printMe() 的 vtable 条目才会更新为指向 Child::printMe

请注意,C++ 像这样工作很好。如果调用的是 Child::printMe ,那么您将在尚未构造的对象上调用成员函数。没有什么好结果。

关于c++ - 覆盖在祖 parent 的构造函数中调用的祖 parent 的虚拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30480532/

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