gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:26:32 25 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/962132/

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