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; }
相关文章推荐
- C++代码学习之一:组合模式例子
- c++——多态、继承、运算符重载综合例子代码
- 微型嵌入式GUI-DOS开发包-编译器-例子代码-组合
- c++继承经典例子
- C++代码模拟对象句柄功能
- C++ 类继承的一个例子
- C++多重继承的例子
- PHP面向对象之旅:接口与组合模拟多继承
- iPhone上模拟摇杆 控制对象的代码例子下载
- c++继承经典例子
- c++继承经典例子
- 高质量C++/C编程指南 -- 第10章 类的继承与组合
- C++箴言:确保公开继承模拟“is-a”
- 高质量C++/C编程指南 -- 第10章 类的继承与组合
- 【转】代码复用原则:合理使用类组合和类继承
- C++学习笔记――继承和组合
- 高质量C++/C编程指南 -- 第10章 类的继承与组合
- c++继承经典例子 .
- 简单使用scipy.weave混合使用Python和C++代码的简单例子
- c++继承经典例子