虚函数在基类与派生类对象的执行过程

#include <iostream>  
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);    你也可以运行这个试试            这是值传递


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

keivin2006

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值