多态性

定义 一个shape抽象类,派生出rectangle类和circle类,计算各类派生类对象的面积area().

#include<iostream>
using namespace std;
class shape{
    public:
        virtual double area()=0;
        
};
class rectangle:public shape{
    public:
        rectangle(double w,double l):width(w),longth(l){
        }
        double area(){
            return (width*longth);
        }
private:
    double width;
    double longth;
};
class circle:public shape{
    public:
        circle(double r):R(r){
        
        }
        double area(){
            return (3.14159*R*R);
        }
private:
    double R;
};
int main()
{
    shape* shape1=new rectangle(4,7);
    shape* shape2=new circle(9);
    cout<<"长方形面积"<<shape1->area()<<endl;
    cout<<"圆形面积"<<shape2->area()<<endl;
    return 0;
}

  有一个交通工具类velicle,将它作为基类派生小车类car,卡车类truck和轮船类boat,定义这些类并定义一个虚函数用来显示各类信息。

 

 1 *#include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class vehicle
 5 {
 6     public:
 7         string name;
 8         public:
 9             vehicle(string h):name(h){
10             }
11         virtual void showinfo() const{
12         cout<<name<<endl;
13     }
14 };
15 class Car: virtual public vehicle{
16     public:
17         double speed;
18         double fuel;
19         public:
20             Car(string h):vehicle(h),speed(200),fuel(14.8){
21             }
22     virtual    void showinfo() const {
23         cout<<name<<endl;
24         cout<<speed<<"km/h"<<endl;
25         cout<<fuel<<"l/100kkm"<<endl;}
26 };
27 class Truck:virtual public vehicle
28 {public:
29     double speed;
30     double fuel;
31     public:
32         Truck(string h):vehicle(h),speed(100),fuel(18.8){
33         }
34     virtual void showinfo() const {
35     cout<<name<<endl;
36     cout<<speed<<"km/h"<<endl;
37     cout<<fuel<<"l/100kkm"<<endl;    }
38 };
39 class Boat:virtual public vehicle
40 {
41     public:
42     double speed;
43     double fuel;
44     public:
45         Boat(string h):vehicle(h),speed(40),fuel(8.8){
46         }
47   virtual    void showinfo() const {
48     cout<<name<<endl;
49     cout<<speed<<"km/h"<<endl;
50     cout<<fuel<<"l/100kkm"<<endl;}
51 };
52 int main()
53 {
54     vehicle *vp;
55     string name0,name1,name2;
56     cin>>name0;
57     Car car(name0);
58     cin>>name1;
59     Truck truck(name1);
60     cin>>name2;
61     Boat boat(name2);
62     vp=&car;
63     vp->showinfo();
64     vp=&truck;
65     vp->showinfo();
66     vp=&boat;
67     vp->showinfo();
68     return 0;
69 }

 

posted @ 2024-05-23 22:35  ZDhr  阅读(8)  评论(0编辑  收藏  举报