基类指针指向派生类对象,调用基类函数,基类函数调用虚函数(派生类已定义)

时间:2022-08-30 09:56:35

A.h

#ifndef A_H
#define A_H
class A
{
public:

virtual void a();
virtual void b();
virtual void c();
};

#endif


A.cpp

#include <iostream>
using std::cout;
using std::endl;
#include "A.h"
void A::a()
{
cout<<"in class A"<<endl;
b();
c();
}
void A::b()
{
cout<<"in class A, function b()"<<endl;
}
void A::c()
{
cout<<"in class A, function c()"<<endl;

}


B.h

#ifndef B_H
#define B_H
#include "A.h"
class B:public A 
{
public:

virtual void b();
virtual void c();

};

#endif

B.cpp

#include <iostream>
using std::cout;
using std::endl;

#include "B.h"


void B::b()
{
cout<<"in class B, function b()"<<endl;
}
void B::c()
{
cout<<"in class B, function c()"<<endl;

}

test.cpp

#include <iostream>
using std::cout;
using std::endl;
#include "A.h"
#include "B.h"

int main()
{
B bbb;

A *ptra = 0;

ptra = &bbb;

ptra->a();

}

结果

[root@hsm test_virtual_func]# ./test
in class A
in class B, function b()
in class B, function c()