#include <iostream>
using namespace std;
static int x;
class A
{
public:
A() {x = 1;}
virtual ~A(){x = 2;}
virtual void foo() {x = 3;}
};
class B :public A
{
public:
B(){x = 4;}
virtual ~B(){x = 5;}
void foo(){x = 6;}
void bar(){foo();}
};
class C:public B
{
public:
C() {x = 7;}
virtual ~C(){x = 8;}
void foo() {x = 9;}
void bar(){foo();}
};
C testc;
void main(void)
{
A *testa = NULL;
B *testb = NULL;
testa = (A*)&testc;
cout << x << endl;
testa->foo();
cout << x << endl;
((B)testc).bar();
cout << x << endl;
testb = new B;
cout << x << endl;
testb->foo();
cout << x << endl;
delete testb;
cout << x << endl;
((B*)(&testc))->bar();
cout << x << endl;
testa = NULL;
cout << x << endl;
}
输出为:
7
9
2
4
6
2
9
9
第三个输出很奇怪,原来 是((B)testc).bar(),原来先转换成一个临时对象,调用bar后会析构,最终调用基类的析构函数
倒数第二个输出,虽然bar不是虚函数,但是当中调用了foo这个虚函数,还是会根据动态类型找到C的foo