gpt4 book ai didi

c++ - 在构造函数中调用虚函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:29 26 4
gpt4 key购买 nike

假设我有两个 C++ 类:

class A
{
public:
A() { fn(); }

virtual void fn() { _n = 1; }
int getn() { return _n; }

protected:
int _n;
};

class B : public A
{
public:
B() : A() {}

virtual void fn() { _n = 2; }
};

如果我写下面的代码:

int main()
{
B b;
int n = b.getn();
}

人们可能希望将 n 设置为 2。

原来n设置为1,为什么?

最佳答案

从构造函数或析构函数调用虚函数是危险的,应尽可能避免。所有 C++ 实现都应调用在当前构造函数的层次结构级别定义的函数版本,而不是进一步调用。

C++ FAQ Lite在第 23.7 节中非常详细地介绍了这一点。我建议阅读该内容(以及常见问题解答的其余部分)以进行跟进。

摘录:

[...] In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”.

[...]

Destruction is done “derived class before base class”, so virtual functions behave as in constructors: Only the local definitions are used – and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.

编辑 更正了大多数(感谢 litb)

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

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