c++中的类和对象_类的对象成为另外一个类的成员
类中有多个对象时:
构造:先构造里面的对象再构造外面的对象 析构:先析构外面的对象再析构里面的对象
#include <iostream>
#include<string.h>
#include<string>
using namespace std;
class phone{
public :
phone(string name){ phone_name=name;
cout<<ph构造<<endl;
}
~phone(){
cout<<ph析构<<endl;
}
string phone_name;
};
class game{
public :
game(string name){ game_name=name;
cout<<p构造<<endl;
}
~game(){
cout<<g析构<<endl;
}
string game_name;
};
class person{
public :
person(string name1,string pName ,string game):name(name),p1(pName),g1(gName){ //若使用有参构造函数初始化对象必须加上无参构造函数否则报错(只写有参会导致默认无参消失,导致下面类无法对实例化对象)
cout<<p构造<<endl;
}
~person(){
cout<<p析构<<endl;
}
void show(){
cout<<name<<"用 "<<p1.phone_name<<" 玩着"<<g1.game_name<<endl;
}
string name;
phone p1;
game g1;
};
void test(){
person xm("bb","mz",”贪吃蛇“);
xm.show();
}
int main(){
test();
return 0;
}
运行结果:ph构造
g构造
p构造
bb用mz玩着tcs
p析构
g析构
ph析构

浙公网安备 33010602011771号