class Shape { protected: int width, height; public: Shape(int a = 0, int b = 0): width(a), height(b) { }//初始化width, height int area() { cout << "Parent class area :" << endl; return 0; } }; class Rectangle : public Shape { public: //Rectangle(int a = 0, int b = 0) :Shape(a, b) { } Rectangle(int a = 0, int b = 0) { width = a; height = b; } int area() { cout << "Rectangle class area :" << width * height << endl; return (width * height); } }; class Triangle : public Shape { public: Triangle(int a = 0, int b = 0) :Shape(a, b) { }//派生类先调用基类构造函数初始化width, height。然后派生类继承变量 int area() { cout << "Triangle class area :" << width * height << endl; return (width * height / 2); } }; // 程序的主函数 int main() { Shape *shape; Rectangle rec(10, 7); Triangle tri(10, 5);
// 存储矩形的地址 shape = &rec; // 调用矩形的求面积函数 area shape->area();
// 存储三角形的地址 shape = &tri; // 调用三角形的求面积函数 area shape->area();
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; } };
运行结果如下:
此时,编译器看的是指针的内容,而不是它的类型。因此,由于 tri 和 rec 类的对象的地址存储在 *shape 中,所以会调用各自的 area() 函数。
class Shape { protected: int width, height; public: Shape( int a=0, int b=0) { width = a; height = b; } // pure virtual function virtual int area() = 0; };
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; //} };