**代碼**:
~~~
#include <iostream>
using namespace std;
class A
{
public:
A()
{
Print();
}
virtual void Print()
{
cout<<"A is constructed.\n";
}
};
class B: public A
{
public:
B()
{
Print();
}
virtual void Print()
{
cout<<"B is constructed.\n";
}
};
int main()
{
A* pA = new B();
delete pA;
return 0;
}
~~~
(感謝網友提供的題目)
**疑**:以上代碼輸出結果是?
輸出結果如下:
A is constructed.
B is constructed.
解釋:當new B()時,因為B繼承了A,所以編譯器首先調用A的構造函數,A的構造函數里是調用A類里的Print(),所以首先輸出A is constructed ,然后調用的是B的構造函數,此時Print虛函數指針已指向B的void print(),所以輸出B is constructed。
======= welcome to my HomePage([*http://blog.csdn.net/zhanxinhang*](http://blog.csdn.net/zhanxinhang)) to have a?communication =======