#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;
/*
4.2 对象的初始化和清理
4.2.7 类对象作为类成员
称为对象成员
当其他类对象作为本类成员时,先构造其他类对象,再构造自身;析构顺序与构造相反
*/
class Phone{
public:
string pname;
Phone(string _pname){
pname = _pname;
cout << "Phone 构造函数" << endl;
}
~Phone(){
cout << "Phone 析构函数" << endl;
}
};
class Person{
public:
string name;
Phone phone;
Person(string _name, string _pname): name(_name), phone(_pname){
// 此处phone(_pname)相当于Phone phone = _pname
// 此为隐式转换法调用构造函数初始化phone对象
cout << "Person 构造函数" << endl;
}
~Person(){
cout << "Person 析构函数" <<endl;
}
};
void test1(){
Person p("张三", "苹果7P");
cout << p.name << "using" << p.phone.pname << endl;
/*
Phone 构造函数
Person 构造函数
张三using苹果7P
Person 析构函数
Phone 析构函数
*/
// 说明:先有phone对象,再有person对象;先结束person对象,再结束phone对象
}
int main(){
test1();
system("pause");
return 0;
}
11.2.7重学C++之【类对象作为类成员】
猜你喜欢
转载自blog.csdn.net/HAIFEI666/article/details/114842337
今日推荐
周排行