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

[c++]多继承

时间:2015-04-15 17:17:09      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:c++   派生      继承   

多继承格式:

class 类名:继承方式1 基类1,继承方式2 基类2,........

#include<iostream>
using namespace std;
class X
{
    int x;
public:
    X(int a = 0)
    {x = a;cout<<"constructing X "<<x<<endl;}
    void set_x(int a)
    {x = a;}
    void show_x()
    {cout<<"x = "<<x<<endl;}
    ~X()
    {cout<<"destructing X "<<x<<endl;}
};
class Y
{
    int y;
public:
    Y(int a = 0)
    {y = a;cout<<"constructing Y "<<y<<endl;}
    void set_y(int b)
    {y = b;}
    void show_y()
    {cout<<"y = "<<y<<endl;;}
    ~Y()
    {cout<<"destructing Y "<<y<<endl;}
};
class Z:public X,public Y//多继承
{
    int z;
public:
    Z(int a = 0,int b = 0,int c = 0):X(a),Y(b)
    {
        z = c;
        cout<<"constructing Z "<<z<<endl;
    }
    void set_xyz(int a,int b,int c)
    {
        set_x(a);
        set_y(b);
        z = c;
    }
    void show_z()
    {
        cout<<"z = "<<z<<endl;

    }
    void show()
    {
        show_x();
        show_y();
        cout<<"z = "<<z<<endl;//类内可直接用
    }
    ~Z()
    {cout<<"destructing Z "<<z<<endl;}
};
int main()
{
    Z obj1(3,4,5);
    Z obj2;
    obj2.set_xyz(10,20,30);
    obj1.show_x();
    obj1.show_y();
    obj1.show_z();
    obj2.show();
    return 0;
}

技术分享

[c++]多继承

标签:c++   派生      继承   

原文地址:http://blog.csdn.net/cherry_ermao/article/details/45059423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!