1.虚函数(impure virtual)
C++的虚函数主要作用是“运行时多态”,父类中提供虚函数的实现,为子类提供默认的函数实现。
子类可以重写父类的虚函数实现子类的特殊化。
2.普通函数(no-virtual)
普通函数是静态编译的,没有运行时多态,只会根据指针或引用的静态类型对象,调用自己的普通函数。
普通函数是父类为子类提供的“强制实现”。
以下代码输出Base
struct Base
{
void print(){ cout << "Base" << endl; } //普通函数
};
struct Pub_Derv :public Base
{
void print() { cout << "Pub_Derv" << endl; } //希望同名隐藏
};
int main()
{
Pub_Derv m;
//基类指针调用print,并不会产生动态绑定
Base *n = &m;
n->print();
}
以下代码输出Pub_Derv
struct Base
{
virtual void print() { cout << "Base" << endl; } //虚函数
};
struct Pub_Derv :public Base
{
void print() override { cout << "Pub_Derv" << endl; } //特殊化的虚函数
};
int main()
{
Pub_Derv m;
//基类指针调用print,产生动态绑定
Base *n = &m;
n->print();
}