#ifndef COMPUTER_H_INCLUDED#define COMPUTER_H_INCLUDED#include<iostream>#include<cstring>#include<iomanip>#include"CPU.h"#include"Memory.h"#include<cstdlib>usingnamespace std;classComputer{public://在组合类中,成员初始化列表的调用顺序不影响构造函数的调用顺序
Computer(string brand,double fre,int cap):cpu(brand,fre),mem(cap){//不能在构造函数里面初始化对象成员,用成员初始化列表
cout<<"A computer is created."<<endl;}~Computer(){
cout<<"A computer is erased."<<endl;}Computer(const Computer &another)cpu(anoter.cpu),mem(another.mem){}voidshow(){
cpu.show();
mem.show();}private://对象成员的初始化顺序取决于定义顺序
CPU cpu;
Memory mem;//注意要有对象成员的初始构造函数};#endif// COMPUTER_H_INCLUDED
#ifndef CPU_H_INCLUDED#define CPU_H_INCLUDED#include<iostream>#include<cstring>#include<iomanip>#include<cstdlib>usingnamespace std;classCPU{public:CPU(string s =" ",double p =0){
brand = s;
main_fre = p;
cout<<"The CPU "<<brand<<" is created"<<endl;}CPU(const CPU &another){//默认拷贝构造函数
brand=another.brand;
main_fre=another.main_gre;}~CPU(){
cout<<"The CPU "<<brand<<" is erased"<<endl;}voidshow(){
cout<<"The brand is "<<brand;
cout<<" and the main frequency is "<<main_fre<<endl;}private:double main_fre;
string brand;};#endif// CPU_H_INCLUDED
#include<iostream>#include<cstring>#include<iomanip>#include<cstdlib>usingnamespace std;classPerson{public:Person(char _name[],int _age){
name =newchar[strlen(_name)+1];strcpy(name,_name);
age = _age;}~Person(){delete[] name;}voidsetName(char _name[]){// delete[] name;// name = new char[strlen(_name)+1];strcpy(name,_name);}voidshow(){
cout<<name<<' '<<age<<endl;}Person(const Person &another){// name = new char[strlen(another.name)+1];// strcpy(name,another.name);
name = another.name;
age = another.age;}private:char*name;int age;};intmain(){
Person person("Tom",18);
Person person2(person);
person.show();
person2.show();
person.setName("Jack");
person.show();
person2.show();return0;}