编程语言
首页 > 编程语言> > C++类对象作为类成员

C++类对象作为类成员

作者:互联网

//当其他类的对象作为本类的成员 构造的时候先去构造类的对象 再去构造自身
//析构函数: 先进后出
先去构造Phone 再去构造Person Person先退出 Phone后退出
//析构与构造顺序相反

点击查看代码
#include<iostream>
using namespace std;
//类对象作为类成员
class Phone
{
public:
	Phone(string PhoneName)
	{
		m_Phone = PhoneName;
		cout << "Phone的构造函数" << endl;
	}
	~Phone()
	{
		cout << "Phone 的析构函数" << endl;
	}
	string m_Phone;
};

class Person
{
public:
	/*Person(string name, Phone phonename) :m_Name(name), m_PhoneName(phonename)
	{
		cout << "Person的初始化列表" << endl;
	}*/
	Person(string name, string phonename) :m_Name(name), m_PhoneName(phonename)//Phone m_PhoneName=phonename;
	{
		cout << "Person的初始化列表" << endl;
	}
	~Person()
	{
		cout << "Person 的析构函数" << endl;
	}
	string m_Name;
	Phone m_PhoneName;
};
//void test01()
//{
//	Phone phone("Vivo");
//	Person p1("zfx",phone );
//	cout << p1.m_Name << "拿着" << p1.m_PhoneName.m_Phone << endl;
//}

void test02()
{
	Person p1("zfx", "Vivo");
	cout << p1.m_Name << "+" << p1.m_PhoneName.m_Phone << endl;

}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

标签:Person,对象,成员,构造,Phone,PhoneName,C++,析构
来源: https://www.cnblogs.com/MegaDataFlowers/p/16483425.html