码迷,mamicode.com
首页 > 编程语言 > 详细

c++继承与派生

时间:2015-05-31 21:32:24      阅读:184      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!