首页 > 编程 > C++ > 正文

C++——继承与组合例子代码(模拟计算机的组成)

2019-11-09 20:41:36
字体:
来源:转载
供稿:网友
#include <iostream>#include <string.h>using namespace std;class Hard{PRivate:    char hname[20];public:    Hard() {};    Hard(char *n)    {        strcpy(hname,n);    };    Hard(const Hard& h)    {        strcpy(hname, h.hname);    }    void Show()    {        cout<<"Hard:"<<hname<<" ";    }};class Soft{private:    char sname[20];public:    Soft() {};    Soft(char *n)    {        strcpy(sname,n);    };    Soft(const Soft& s)    {        strcpy(sname, s.sname);    }    void Show()    {        cout<<"Soft:"<<sname<<" ";    }};class Computer:public Hard,public Soft{private:    char  cname[20];public:    Computer() {};    Computer(char * cn,Hard& h, Soft& s):Hard(h),Soft(s)    {        strcpy(cname,cn);    };    Computer(char * cn,char * hn, char * sn):Hard(hn),Soft(sn)    {        strcpy(cname,cn);    };    void Show()    {        cout<<"Computer:"<<cname<<" ";        Hard::Show();        Soft::Show();        cout<<endl;    }};class Computer2{private:    char  cname[20];    Hard hard;    Soft soft;public:    Computer2() {};    Computer2(char * cn,Hard& h, Soft& s):hard(h),soft(s)    {        strcpy(cname,cn);    };    Computer2(char * cn,char * hn, char * sn):hard(hn),soft(sn)    {        strcpy(cname,cn);    };    void Show()    {        cout<<"Computer2:"<<cname<<" ";        hard.Show();        soft.Show();        cout<<endl;    }};int main(){    Hard h("cpu");    Soft s("Windows xp");//继承    Computer c1("leno",h,s);    Computer c2("leno","cpu","Windows 7");    c1.Show();    c2.Show();//组合    Computer2 c3("leno",h,s);    Computer2 c4("leno","cpu","windows 7");    c3.Show();    c4.Show();    return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选