C++ 多态
虚函数
虚函数 是在基类中使用关键字 virtual 声明的函数。
在派生类中重新定义基类中定义的虚函数时,
会告诉编译器不要静态链接到该函数。
我们想要的是在程序中任意点
可以根据所调用的对象类型来
选择调用的函数,
这种操作被称为动态链接,或后期绑定。
area() 的声明前放置关键字 virtual,
class Shape
{
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area ()
{
cout << "parent Shape area" << endl;
return 0;
}
private:
};
class Recrangle : public Shape
{
public :
Recrangle(int a = 0, int b = 0) : Shape(a, b)
{
}
int area()
{
cout << "child Recrangle area" << endl;
return 0;
}
};
class Triangle : public Shape
{
public :
Triangle(int a = 0, int b = 0) :Shape(a, b)
{
}
int area()
{
cout << "traingle class area:" << endl;
return (width * height / 2);
}
};
int main()
{
Shape* shape;
Recrangle rec(10, 7);
Triangle tri(10, 5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
打印结果:
child Recrangle area
traingle class area:
纯虚函数
您可能想要在基类中定义虚函数,
以便在派生类中重新定义该函数更好地适用于对象,
但是您在基类中又不能对虚函数给出有意义的实现,
这个时候就会用到纯虚函数。
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area() = 0;
};
= 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。