首页 > 代码库 > 虚函数重写

虚函数重写

// 单继承虚函数无overload.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

class Parent{
public:
virtual void fun1(){
}
virtual void fun2(){
}
};

class Sun:public Parent{
public:
virtual void fun3(){
}
virtual void fun4(){
}
};


class Parent1{
public:
virtual void fun1(){
printf("Parent1======fun1======\n");
}
virtual void fun2(){
printf("Parent1======fun2======\n");
}
};

class Sun1:public Parent1{
public:
virtual void fun1(){ //虚函数fun1重写
printf("Sun======= fun1=======\n");
}
virtual void fun2(){ //虚函数fun2重写
printf("Sun======= fun2=======\n");
}
};


void test1(){ //测试虚函数无重写函数
Sun sun;
Sun* ps=&sun;
printf(" 对象首地址即this的地址是:%x\n",ps); //18ff44
int* point=(int*)ps;
int* addr=(int*)(*point);
printf("虚函数的地址为:%x\n",addr);
sun.fun1();

for(int i=0;i<4;i++){
printf("%x\n",*(addr+i));
}
}

void test2(){
Sun1 sun;
Parent1 parent1;
Sun1* ps=&sun;
printf(" 对象首地址即this的地址是:%x\n",ps); //
int* point=(int*)ps;
int* addr=(int*)(*point);
printf("虚函数的地址为:%x\n",addr);
sun.fun1();
parent1.fun1();
for(int i=0;i<4;i++){
printf("%x\n",*(addr+i));
}
}


int main(int argc, char* argv[])
{
test2();
printf("Hello World!\n");
return 0;
}

 

虚函数重写