using namespace std;
class A
{
public:
int m;
A()
{
cout << "gouzao A" << endl;
m = 1;
}
~A()
{
cout << "xigou A" << endl;
}
virtual void print()
{
cout << "A: " << m << endl;
}
};
class B: public A
{
public:
B()
{
cout << "gouzao B" << endl;
m = 2;
}
~B()
{
cout << "xi gou B" << endl;
}
void print()
{
cout << "B: " << m << endl;
}
};
class C: public B
{
public:
C()
{
cout << "gouzao C" << endl;
m = 3;
}
~C()
{
cout << "xi gou C" << endl;
}
void print()
{
cout << "C: " << m << endl;
}
};
void printClass(A a)
{
cout << "A address: " << &a << endl;
a.print();
}
void printClassE(A* a)
{
cout << "EA address: " << a << endl;
((A*)a)->print();
}
void testfunc()
{
C c;
c.print();
//cout << "C address: " << &c << endl;
//printClass(c);
C* pc= new C();
A* pa= (A*)pc;
printClassE(pa);
}
int main()
{
testfunc();
system("pause");
return -1;
}
你觉得应该输出什么呢?
为什么?
为什么都是调用的c的print
删掉c类中的这个函数
void print()
{
cout << "C: " << m << endl;
}
又是怎么样的结果
这得看你对虚函数表的理解 ,和值传递和指针传递的理解了,
//printClass(c); 你也可以运行这个试试 这是值传递