读书人

虚函数有关问题请问

发布时间: 2013-01-07 10:02:24 作者: rapoo

虚函数问题请教
请教一下,虚函数,即在函数前加virtual;当被定为虚函数的时候,到底发生了什么?或者说处理器需要额外做了哪些工作?
比如下面程序:

#include<iostream>
using namespace std;

class Vehicle
{
public:
Vehicle(float speed,int total)
{
Vehicle::speed=speed;
Vehicle::total=total;
}
virtual void ShowMember()
{
cout<<speed<<"|"<<total<<endl;
}
virtual ~Vehicle()
{
cout<<"载入Vehicle基类析构函数"<<endl;
}

protected:
float speed;
int total;
};

class Car:public Vehicle
{
public:
Car(int aird,float speed,int total):Vehicle(speed,total)
{
Car::aird=aird;
}
void ShowMember()
{
cout<<speed<<"|"<<total<<"|"<<aird<<endl;
}
virtual ~Car()
{
cout<<"载入Car派生类析构函数"<<endl;
}
protected:
int aird;
};

void test(Vehicle &temp)
{
temp.ShowMember();
}

void DelPN(Vehicle *temp)
{
delete temp;
}

void test25()
{
Car* a=new Car(100,1,1);
a->ShowMember();
DelPN(a);

}


对于以上程序,出现两对虚构函数:
1. ShowMember虚函数,因为在父类Vehicle中和在子类Vehicle中都有,所以加上virtual,作为虚函数,可让编译器在进行Vehicle参数传递引用做处理的时候,能有所区分,具体是要调用父类的Showmember还是子类的Showmember。
2.另外一对虚函数,连名字都不一样,一个是~Vehicle,另一个是~Car,这个还需要加virtual?
如果不加,上述程序在退出时,还是只会调用~Vehicle,而不需要调用~Car;
另外只需要在父类析构函数加一个virtual就可以了。
请问加上virtual以后,编译器,处理器都做了哪些相应的处理?
谢谢!
[解决办法]
虚函数 编译器做迟后联编

读书人网 >C语言

热点推荐