您的位置:首页 > 其它

调用哪个虚函数的问题

2010-08-09 20:24 162 查看
#include<iostream>
#include<string>
usingnamespacestd;
classA{
public:
voidvirtualf()
{
cout<<"A"<<endl;
}
};
classB:publicA{
public:
voidvirtualf(){
cout<<"B"<<endl;
}
};
intmain()
{
A*pa=newA();
pa->f();
B*pb=(B*)pa;
pb->f();
deletepa,pb;
pa=newB();
pa->f();
pb=(B*)pa;
pb->f();
getchar();
return0;
}


.codearea{color:black;background-color:white;line-height:18px;border:1pxsolid#4f81bd;margin:0;width:auto!important;width:100%;overflow:auto;text-align:left;font-size:12px;font-family:"CourierNew","Consolas","Fixedsys","BitStreamVeraSansMono",courier,monospace,serif}
.codeareapre{color:black;line-height:18px;padding:00012px!important;margin:0em;background-color:#fff!important}
.linewrappre{white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;word-break:normal}
.codeareapre.alt{background-color:#f7f7ff!important}
.codearea.lnum{color:#4f81bd;line-height:18px}

运行结果:





分析:


1)虚函数是占用空间的,含有1个虚函数的类的对象,其内部有一个虚函数指针,所以其sizeof大小为各个成员变量大小之和,在加上虚函数指针的大小(一般为4B,32位机器)。

2)当通过基类指针或子类指针调用虚函数的时候,都是通过该指针当前指向的对象中的虚函数指针来调用合适的虚函数。所以,无论该指针为基类类型、子类类型,调用哪个虚函数都取决于其所指向的对象的类型(实际依赖对象中的虚函数指针)。

3)通过类对象调用虚函数,理所当然调用的是该对象类类型的虚函数。

#include<iostream>
#include<string>
usingnamespacestd;

classA{
public:
intval;
A(inti=1):val(i){};
intvirtualf()
{
returnval;
}
};

classB:publicA{
public:
intval;
B(inti=2):val(i){};
};

intmain()
{
Bb;
cout<<b.f()<<endl;
getchar();
return0;
}

输出:

结果为1。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
章节导航