#include <iostream> using namespace std; class Shape { public:
//普通函式前加virtual,普通函式變成了虛函式
// =0表示抽象虛函式,子類必須實作該函式 virtual void printarea()=0; void hello(){cout<<"Shape hello function"<<endl;}; }; class Circle:public Shape { public: Circle(int a):r(a){} void hello(){cout<<"Circle hello function"<<endl;}; void printarea(){cout<<"圓形面積為:"<<r*r*3.14<<endl;} private: int r; }; class Rectangle:public Shape { public: Rectangle(int a,int b):x(a),y(b){} void hello(){cout<<"Rectangle hello function"<<endl;}; void printarea(){cout<<"矩形面積為:"<<x*y<<endl;} private: int x; int y; }; class Square:public Shape { public: Square(int a):l(a){} void hello(){cout<<"Square hello function"<<endl;}; void printarea(){cout<<"正方形面積為:"<<l*l<<endl;} private: int l; }; void prints(Shape *s) {
//基類指標s指向子類物件
//s呼叫的函式printarea是虛函式,所以會呼叫子類實體的printarea s->printarea();
//s呼叫的函式hello不是虛函式,所以只會呼叫基類的hello s->hello(); } int main() { Circle a(1); prints(&a); Square b(2); prints(&b); Rectangle c(1,2); prints(&c); return 0; }
輸出:
圓形面積為:3.14 Shape hello function 正方形面積為:4 Shape hello function 矩形面積為:2 Shape hello function
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/45001.html
標籤:C++
上一篇:高精度加法實作(c++)
