在构造函数内调用虚函数 [英] Calling virtual functions inside constructors
本文介绍了在构造函数内调用虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个C ++类:
Suppose I have two C++ classes:
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; }
};
如果我写下面的代码:
main()
{
B b;
int n = b.getn();
}
可能会期望 n
设置为2。
结果是 n
设置为1.为什么?
It turns out that n
is set to 1. Why?
推荐答案
从构造函数或析构函数调用虚函数很危险,应尽可能避免。所有C ++实现应该调用在当前构造函数中层次结构级别定义的函数的版本,而不再进一步。
Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.
C ++ FAQ Lite 在第23.7节中非常详细地介绍了这一点。
The C++ FAQ Lite covers this in section 23.7 in pretty good detail. I suggest reading that (and the rest of the FAQ) for a followup.
编辑更正最常用于所有(感谢litb)
EDIT Corrected Most to All (thanks litb)
这篇关于在构造函数内调用虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文