C++ 多态(一)
Polymorphism in C++
概述
多态这个词的意思是有多种形式。通常,多态发生在类的层次结构中,它们通过继承相互关联。
C++ 多态意味着对成员函数的调用将导致执行不同的函数,这取决于调用该函数的对象类型。
实例
考虑下面的例子,其中一个基类 Shape,由其派生出两个派生类:Rectangle 和 Triangle。
#include <iostream>
using namespace std;
class Shape
{
public:
Shape(int a = 0, int b = 0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
protected:
int width, height;
};
class Rectangle: public Shape
{
public:
Rectangle(int a = 0, int b = 0):
Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangl