多态
在C++中存在多态,什么叫多态呢?从字面上来看,多种形态简称为多态。当类之间通过继承关联时,就用到了多态。C++多态意味着调用成员函数时会根据调用函数的对象的类型来执行不同的函数。
#include <iostream>
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 << "area method of the Shape!" << endl;
return 0;
}
};
class Rectangle :public Shape{
public:
Rectangle(int a = 0,int b = 0):Shape(a,b){}
int area()
{
cout << "area method of Rectangle!" << endl;
return 0;
}
};
class Triangle:public Shape{
public:
Triangle(int a = 0,int b = 0):Shape(a,b){}
int area()
{
cout << "area method of Triangle!" << endl;
return 0;
}
};
int main()
{
Shape *shape;
Rectangle rect(2,3);
Triangle tri(3,4);
shape = ▭
shape->area();
shape = &tri;
shape->area();
return 0;
}
运行结果:
area method of Rectangle!
area method of Triangle!
在这里需要注意的是,需要将父函数中的area函数声明为virtual类型,这样在编译时就不会被编译器设置为基类中的版本。如果不声明virtual类型,调用函数area()被编译器设置为基类中的版本,这就是所谓的静态多态。函数调用在程序执行前就准备好了。因此的它的运行结果会有所不同:
area method of the Shape!
area method of the Shape!
使用virtual声明的函数叫虚函数,在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数。我们想要的是在程序中任意点可以根据所调用的对象类型来选择调用的函数,这种操作叫做动态链接。
纯虚函数
基类中定义虚函数,为了在派生类中重新定义该函数更好的适用于对象,但在基类中又不能对对函数给出有意义的实现,这时候就会用到纯虚函数。
纯虚函数定义:
class Shape{
protected:
int width,height;
public:
Shape(int a = 0,int b = 0)
{
width = a;
height = b;
}
virtual int area() = 0;
};
=0告诉编译器该函数没有主体,这个函数就是纯虚函数。