virtual 关键字定义虚函数
多态是通过指向虚函数表的虚指针实现的。
D d;
d.f2(); // 注意实际调用 B::f2(); 而B::f2() 中调用了 f1(); 是通过虚指针调用的 (VPTR[0])(); 是调用了D::f1();
d.B::f1(); // 明确指定调用 B::f1(); 没有通过虚指针
d.f1(); // 通过虚指针和虚表调用 D::f1();
d.D::f1(); //调用D::f1();
例子
#include <stdio.h>
class CParent
{
public:
void Intro() {
printf("I'm a Parent, ");
Hobby();
}
virtual void Hobby() {
printf("I like football!");
}
};
class CChild : public CParent {
public:
void Intro() {
printf("I'm a Child, ");
Hobby();
}
void Hobby() {
printf("I like basketball!\n");
}
};
int main(int agc, char *arv[]) {
CChild *pChild = new CChild();
CParent *pParent = (CParent*)pChild;
pParent->Intro();
return 0;
}
#include <stdio.h>
#include <iostream>
using namespace std;
class A
{
protected:
int m_data;
public:
A(int data = 0)
{
m_data = data;
}
int GetData()
{
return doGetData();
}
virtual int doGetData()
{
return m_data;
}
};
class B: public A
{
protected : int m_data;
public:
B(int data = 1)
{
m_data = data;
}
int doGetData()
{
return m_data;
}
};
class C : public B
{
protected : int m_data;
public :
C(int data = 2)
{
m_data = data;
}
};
int main()
{
C c(10);
cout<<c.GetData() << endl;
cout<<c.A::GetData()<<endl;
cout<<c.B::GetData()<<endl;
cout<<c.C::GetData()<<endl;
cout<<c.doGetData()<<endl;
cout<<c.A::doGetData()<<endl;
cout<<c.B::doGetData()<<endl;
cout<<c.C::doGetData()<<endl;
return 0;
}
/*
结果: 1 1 1 1 1 0 1 1
*/