首页 > 编程语言 > 详细

c++继承与派生

时间:2015-05-31 21:30:14      阅读:278      评论:0      收藏:0      [点我收藏+]

<1>.公有继承

#include <iostream>
using namespace std;
class vehicle
{
private:
    float weight;
    int wheels;
public:
    vehicle(int in_wheels,float in_weight)
    {
        wheels=in_wheels;
        weight=in_weight;
    }
    int get_wheels()
    {
        return wheels;
    }
    float get_weight()
    {
        return weight;
    }

};
class car:public vehicle
{
private:
    int passenger_load;
public:
    car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight)
    {
        passenger_load=people;
    }
    int get_passenger()
    {
        return passenger_load;
    }
};
int main()
{
    car bm(4,100);
    cout<<bm.get_wheels()<<endl;
    cout<<bm.get_weight()<<endl;
    cout<<bm.get_passenger()<<endl;
    return 0;
}

结果:

4

100

5

<2>.私有继承

#include <iostream>
using namespace std;
class vehicle
{
private:
    float weight;
    int wheels;
public:
    vehicle(int in_wheels,float in_weight)
    {
        wheels=in_wheels;
        weight=in_weight;
    }
    int get_wheels()
    {
        return wheels;
    }
    float get_weight()
    {
        return weight;
    }

};
class car:private vehicle
{
private:
    int passenger_load;
public:
    car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight)
    {
        passenger_load=people;
    }
    int get_passenger()
    {
        return passenger_load;
    }
    int get_wheels()
    {
        return vehicle::get_wheels();
    }
    int get_weight()
    {
        return vehicle::get_weight();
    }
};
int main()
{
    car bm(4,100);
    cout<<bm.get_wheels()<<endl;
    cout<<bm.get_weight()<<endl;
    cout<<bm.get_passenger()<<endl;
    return 0;
}

 

结果:

4

100

5

<3>.保护继承

#include <iostream>
using namespace std;
class vehicle
{
private:
    int wheels;
protected:
    float weight;
public:
    vehicle(int in_wheels,float in_weight)
    {
        wheels=in_wheels;
        weight=in_weight;
    }
    int get_wheels()
    {
        return wheels;
    }
    float get_weight()
    {
        return weight;
    }

};
class car:protected vehicle
{
private:
    int passenger_load;
public:
    car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight)
    {
        passenger_load=people;
    }
    int get_passenger()
    {
        return passenger_load;
    }
    int get_wheels()
    {
        return vehicle::get_wheels();
    }
    int get_weight()
    {
        return weight;
    }
};
int main()
{
    car bm(4,100);
    cout<<bm.get_wheels()<<endl;
    cout<<bm.get_weight()<<endl;
    cout<<bm.get_passenger()<<endl;
    return 0;
}

 

结果:

4

100

5

 

c++继承与派生

原文:http://www.cnblogs.com/liujunming/p/4540950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!