//例子
#include <iostream>
using namespace std;
#include <string>
class Animal{
string name;
public:
virtual void eat()=0;//一定不会被执行,纯虚函数
virtual void sleep(){
cout << "动物休息" << endl;
}
virtual void shout(){
cout << "动物叫" << endl;
}
};//注意分号
class Cat : public Animal{
public:
virtual /* virtual 可写可不写 */ void eat(){
cout << "猫写猫粮" << endl;
}
void sleep(){
cout << "猫睡觉" << endl;
}
void shout(){
cout << "猫喵喵叫" << endl;
}
};//注意分号
class Dog : public Animal{
public :
void eat(){
cout << "狗吃骨头" << endl;
}
void sleep(){
cout << "狗在睡觉" << endl;
}
void shout(){
cout << "我叫旺财" << endl;
}
};//分号不能少
class JiaFei : public Cat{
public :
void eat(){
cout << "加非猫爱吃意大利面" << endl;
}
void sleep(){
cout << "加非猫睡在沙发上" << endl;
}
void shout(){
cout << "加非猫说下午好" << endl;
}
}; // 分号
class Player{
string name;
public :
Player( string n ) : name(n){}
void play( Animal* p/*指针*/ ){
p->eat();
p->sleep();
p->shout();
}
void play( Animal& p /*引用*/){
p.eat();
p.sleep();
p.shout();
}
};// 分号
typedef void (*fun)(void);
int main()
{
//cout << sizeof(Animal) << endl; //输出8
Cat c;
Dog d;
JiaFei j;
Player p1( "小小" );
Player p2( "蔡依林");
p1.play(&c);
p2.play(&d);
p2.play(&j);
Cat *pc=&c;
Dog *pd=&d;
cout<<(int*)pc<<endl;
cout<<sizeof(*(int*)pc)<<endl;
cout<<sizeof(Animal)<<endl;
cout<<sizeof()<<endl;
return 0;
}
虚函数表代码示例
#include <iostream.h>
typedef void (*Fun)(void);
class Base {
public:
virtual void f(){cout<<"Base::f"<<endl;}
virtual void g(){cout<<"Base::g"<<endl;}
virtual void h(){cout<<"Base::h"<<endl;}
};
int main(){
Base b;
Fun pFun = NULL;
cout<<"虚函数表地址:"<<(int*)(&b)<<endl;
cout<<"虚函数表 — 第一个函数地址:"<<(int*)*(int*)(&b)<<endl;
pFun = (Fun)*((int*)*(int*)(&b));
pFun();
pFun = (Fun)*(1+(int*)*(int*)(&b));
pFun();
pFun = (Fun)*(2+(int*)*(int*)(&b));
pFun();
return 0;
}