您的位置:首页 > 理论基础

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

2017-02-09 08:57 387 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: