1.如果期望派生类重新定义一个成员函数,那么应该在基类中把此函数设为virtual
2.以单一指令调用不同函数,这种性质称为多态
3.虚函数是C++语言的多态性质和动态绑定的关键
4.既然抽象类中的虚函数不打算被调用,我们就不应该定义它,应该把它定义为纯虚函数(在函数声明之后加上“=0”即可)
5.拥有纯虚函数者为抽象类,以区别于所谓的具体类
6.抽象类不能产生出对象实例,但是我们可以拥有指向抽象类的指针,以便于操作抽象类的各个派生类
7.虚函数派生下去仍为虚函数,但可以省略virtual关键字
#include <iostream>
#include <stdio.h>
using namespace std;
class Base
{
public:
int m_data1;
public:
virtual void print_self(){cout<<"base class"<<endl;}
};
class A1:public Base
{
public:
int m_data2;
public:
void set_self(int m, int n){m_data1 = m;m_data2 = n;}
virtual void print_self(){cout<<"m_data1="<<m_data1<<","<<"m_data2="<<m_data2<<endl;}
};
class A2:public Base
{
public:
int m_data3;
public:
void set_self(int m, int n){m_data1 = m;m_data3 = n;}
virtual void print_self(){cout<<"m_data1="<<m_data1<<","<<"m_data3="<<m_data3<<endl;}
};
int main(void)
{
A1 a1;
A2 a2;
Base *pBase = &a1;
a1.set_self(1,11);
pBase->print_self();
pBase = &a2;
a2.set_self(2,22);
pBase->print_self();
return 0;
}
若把Base类中的virtual去掉,则两行输出都为“base class”