实验6 类的继承和多态

Posted perservence

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实验6 类的继承和多态相关的知识,希望对你有一定的参考价值。

//6-1
#include <iostream> using namespace std; class A{ public: A(int a,int b):m(a),n(b){} int add(){ cout<<"m+n= "<<m+n<<endl; } private: int m,n; }; class B:public A{ public: B(int a,int b):A(a,b){ m=a; n=b; } int minus(){ cout<<"m-n= "<<m-n<<endl; } private: int m,n; }; class C:public A{ public: C(int a,int b):A(a,b){ m=a; n=b; } int multiply(){ cout<<"m*n= "<<m*n<<endl; } private: int m,n; }; class D:public A{ public: D(int a,int b):A(a,b){ m=a; n=b; } int division(){ cout<<"m/n= "<<m/n<<endl; } private: int m,n; }; int main(){ B b(30,15); b.add(); b.minus(); C c(30,2); c.add(); c.multiply(); D d(30,3); d.add(); d.division(); return 0; }

技术分享图片

 

 

//6-2
#include <iostream>
using namespace std;
class vehicle{
    public:
        vehicle(int m,int w):maxspeed(m),weight(w){
            cout<<"maxspeed= "<<maxspeed<<endl;
            cout<<"weight= "<<weight<<endl;
        }
        ~vehicle(){}
        void run(){
            cout<<"run"<<endl;
        }
        void stop(){
            cout<<"stop"<<endl;
        }
    private:
        int maxspeed,weight;
}; 
class bicycle:virtual public vehicle{
    public:
        bicycle(int m,int w,int h):vehicle(m,w){
            height=h;
            cout<<"height is:"<<height<<endl;
        }
        ~bicycle(){}
    private:
        int height;
};
class motorcar:virtual public vehicle{
    public:
        motorcar(int m,int w,int s):vehicle(m,w){
            seatnum=s;
            cout<<"seatnum is "<<seatnum<<endl;
        }
        ~motorcar(){}
    private:
        int seatnum;
};
class motorcycle:public bicycle,public motorcar{
    public:
        motorcycle(int m,int w,int h,int s):vehicle(m,w),motorcar(m,w,s),bicycle(m,w,h){}
        ~motorcycle(){}
};
int main(){
    vehicle v(150,100);
    v.run();
    v.stop();
    motorcar a(100,75,2);
    a.run();
    a.stop();
    bicycle b(50,30,1);
    b.run();
    b.stop();
    motorcycle c(100,50,1,2);
    c.run();
    c.stop();
    return 0;
}

 

 技术分享图片

 


以上是关于实验6 类的继承和多态的主要内容,如果未能解决你的问题,请参考以下文章

实验6 类的继承和多态

实验4 类的继承派生和多态

实验五--类的继承派生多态二次练习

c++实验四 类的继承派生和多态

实验三 类的继承和多态性

实验四 类的继承派生和多态