12.4c++中的继承

#include 

using namespace std;

class Sofa
{
private:
    string way;
    int *score;
public:
    Sofa(){}
    //有参构造函数
    Sofa(string way,int score):way(way),score(new int(score))
    {cout << "Sofa::有参构造函数" << endl;}
    //拷贝构造函数
    Sofa(const Sofa &other):way(other.way),score(new int(*(other.score)))
    {cout << "Sofa::拷贝构造函数" << endl;}
    //拷贝赋值函数
    Sofa &operator=(const Sofa &other)
    {
        if(this != &other)
        {
            way = other.way;
            score=new int(*(other.score));
        }
        cout << "Sofa::拷贝赋值函数" << endl;
        return *this;
    }
    //析构函数
    ~Sofa()
    {
        delete score;
        cout << "Sofa::析构函数" << endl;
    }
    void show()
    {
        cout << way << endl;
        cout << *score << endl;
    }

};

class Bed
{
private:
    string sleep;
    int *score;
public:
    Bed(){}
    Bed(string sleep,int score):sleep(sleep),score(new int(score))
    {
        cout << "Bed::有参构造函数" << endl;
    }

    Bed(const Bed &other):sleep(other.sleep),score(new int(*(other.score)))
    {cout << "Bed::拷贝构造函数" << endl;}
    Bed &operator=(const Bed &other)
    {
        if(this != &other)
        {
            sleep=other.sleep;
            score=new int(*(other.score));
        }
        cout << "Bed::拷贝赋值函数" << endl;
        return *this;
    }
    ~Bed()
    {
        delete score;
        cout << "Bed::析构函数" << endl;
    }
    void show()
    {
        cout << sleep << endl;
        cout << *score << endl;
    }
};

class Sofa_Bed:public Sofa,public Bed
{
private:
    string color;
public:
    Sofa_Bed(){}
    Sofa_Bed(string way,int score,string sleep,int scoreB,string color):Sofa(way,score),Bed(sleep,scoreB),color(color)
    {cout << "Sofa_Bed::有参构造函数" << endl;}
    Sofa_Bed(const Sofa_Bed &other):Sofa(other),Bed(other),color(other.color)
    {cout << "Sofa_Bed::拷贝构造函数" << endl;}
    Sofa_Bed &operator=(const Sofa_Bed &other)
    {
        if(this != &other)
        {
            Sofa::operator=(other);
            Bed::operator=(other);
            color=other.color;
        }
        cout << "Sofa_Bed::拷贝赋值函数" << endl;
        return *this;
    }
    ~Sofa_Bed()
    {
        cout << "Sofa_Bed::析构函数" << endl;
    }
    void show()
    {
        Sofa::show();
        Bed::show();
        cout << color << endl;
    }
};
int main()
{
    Sofa_Bed s1("坐",10,"躺",9,"红");
    Sofa_Bed s2(s1);
    Sofa_Bed s3=s2;
    s1.show();
    return 0;
}

12.4c++中的继承_第1张图片12.4c++中的继承_第2张图片

你可能感兴趣的:(c++,算法,开发语言)