0
点赞
收藏
分享

微信扫一扫

类对象作类成员

Phone类

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<string>

//这是定义类
class Phone
{
public:
	Phone()
	{
		cout << "Phone空参构造" << endl;
	}

	Phone(string brand, int price)
	{
		this->brand = brand;
		this->price = price;
		cout << "Phone有参构造1" << endl;

	}
	Phone(string brand)
	{
		this->brand = brand;
		cout << "Phone有参构造2" << endl;

	}

	Phone(const Phone& p)
	{
		this->brand = p.brand;
		this->price = p.price;
		cout << "Phone拷贝构造" << endl;
	}

public:
	string brand;
	int price;
};


Person类

class Person
{
public:
	Person()
	{
		cout << "Person空参构造" << endl;
	}

	//Person(Phone& p):phone(p) //使用初始化列表初始化 Phone拷贝构造
	//{
	//	
	//	cout << "Person有参构造" << endl;
	//}

	Person(Phone& p) 
	{

		cout << "Person有参构造" << endl;
		this->phone = p; //不使用初始化列表初始化  Phone空参构造
	}

	//Person(string brand) :phone(brand)
	//{

	//	cout << "Person有参构造" << endl;

	//}

	Person(const Person& p)
	{
		/*this->phone = new Phone(*p.phone);*/
	
	}

	void show()
	{
		cout << &this->phone << endl;
	}
	
	~Person()
	{
		//if (phone != NULL)
		//{
		//	delete phone;
		//	phone = NULL;
		//}
	}
public:
	Phone phone;//不允许使用不完整的类型
};


Test

void test()
{
	Phone phone("小米", 1500);
	cout << &phone << endl;
	Person person(phone);
	person.show();
}

举报

相关推荐

0 条评论