虚函数是C++实现多态的重要工具。
考虑一种情况,现在有形状这个基类,给基类有一个area()函数,如下
class Shape {
int area(){...}
}
在其派生类中重写这个方法
class A : public Shape{
int area(){...}
}
class B : public Shape{
int area(){...}
}
int main(){
Shape* shape;
A a;
B b;
shape = &a;
shape.area();
shape = &b;
shape.area();
return 0;
}
此时两个shape.area()到底调用了哪一个函数?
结果是shape.area() 调用了基类的area方法。
如果要调用派生类的函数,需要使用虚函数,如下:
#include这是为什么?using namespace std; class Shape { protected: int width, height; public: Shape(int a = 0, int b = 0) { width = a; height = b; } // 虚函数 virtual int area() { cout << "Parent class area :" << endl; return 0; } // 纯虚函数 virtual int Perimeter() = 0; void test() { cout << "test" << endl; } }; class A :public Shape { public: A(int a = 0, int b = 0) :Shape(a, b) {} // 虚函数 int area() { cout << "A class area :" << endl; return 0; } // 纯虚函数 int Perimeter() { return 1; } void test() { cout << "A" << endl; } }; class B :public Shape { public: B(int a = 0, int b = 0) :Shape(a, b) {} // 虚函数 int area() { cout << "B class area :" << endl; return 0; } // 纯虚函数 int Perimeter() { return 2; } void test() { cout << "B" << endl; } }; int main() { A a(1, 2); B b(1, 2); a.area(); a.Perimeter(); b.area(); b.Perimeter(); Shape* shape; shape = &a; shape->area(); shape->Perimeter(); shape->test(); shape = &b; shape->area(); shape->Perimeter(); shape->test(); return 0; }
首先:案例一中的现象叫 静态多态(或者静态链接、早绑定)
这意味着在程序编译阶段shape->area()就确定函数的入口是基类的area()函数。
案例二中真正实现了多态,virtual关键字告诉编译器不要在编译阶段绑定shape->area(),而是在执行阶段选择函数入口。
纯虚函数纯虚函数在基类不实现,即只定义了函数,而没有具体实现。在其派生类中必须实现。(纯虚函数类似与Java中的Interface)而且纯虚函数有“=0”的后缀



