1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>
using namespace std;
 
class Base
{
	public:
		Base()
		{
			foo();
		}
		virtual void foo()
		{
			cout<<"Base::foo()"<<endl;
		}
};
 
class Derived:public Base
{
	public:
		virtual void foo()
		{
			cout<<"Derived::foo()"<<endl;
		}
};
 
int
main()
{
	Derived * pD = new Derived;
	pD->foo();
	return 0;
}

程序输出为:

Base::foo()
Derived::foo()

而不是

Derived::foo()
Derived::foo()

原因是,基类的构造函数调用的foo()是基类的,而不是被子类重写过的foo(),构造基类时,vtable还没有被正确的书写。使我注意到这个问题的是酷壳关于Java类成员构造的一篇文章:Java构造时成员初始化的陷阱

Tags: ,.
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

RFC: Request For Comments. Orz..

Name(required)
Mail (required),(will not be published)

RFC: Request For Comments. Orz..

Website(recommended)