学习日志3.11

1.深拷贝与浅拷贝

#include<iostream>
#include<string>
using namespace std;
class person
{
public:
	person()
	{
		cout << "person的默认构造函数调用" << endl;
	}
	person(int age,int height)
	{
		m_height = new int(height);//将height存放到堆区
		cout << "person的有参构造函数调用" << endl;
		m_age = age;
	}
	int m_age;
	int* m_height;//身高,指向堆区
	//拷贝构造
	person(const person& p)
	{
		cout << "person的拷贝构造函数" << endl;
		m_age = p.m_age;
		//m_height = p.m_height;编译器给的拷贝构造函数,堆区重复释放

		//深拷贝
		m_height = new int(*p.m_height);
	}
	~person()
	{
		cout << "person的析构构造函数调用" << endl;
		//将堆区开辟的数据释放
		if (m_height != NULL)
		{
			delete m_height;
			m_height = NULL;
		}
	}
};
void text1()
{
	person p1(18,160);
	cout << "p1的年龄为:" << p1.m_age << "身高为:" <<* p1.m_height << endl;
	person p2(p1);
	cout << "p2的年龄为:" << p2.m_age << "身高为:" << *p2.m_height << endl;//浅拷贝,由系统提供
}

int main()
{
	text1();
	  
	system("pause");
	return 0;
}

运行结果:

 2.初始化列表

#include<iostream>
#include<string>
using namespace std;

//初始化列表
class person
{
public:

	//传统初始化操作
	/*person(int a, int b, int c)
	{
		m_A = a;
		m_B = b;
		m_C = c;
	}*/

	//初始化列表初始化属性
	person(int a,int b,int c) :m_A(a), m_B(b), m_C(c) {
		cout << "初始化列表" << endl;
	}
	int m_A;
	int m_B;
	int m_C;
};

void text1()
{
	//person p(10, 20, 30);
	person p(10,20,30);
	cout << "m_A= " << p.m_A << endl;
	cout << "m_B= " << p.m_B << endl;
	cout << "m_C= " << p.m_C << endl;
	
}
int main()
{
	text1();
	  
	system("pause");
	return 0;
}

运行结果:

 3.类对象作为类成员(简称套娃)

#include<iostream>
#include<string>
using namespace std;

//类对象作为类成员
class Phone
{
public:
	Phone(string pName)
	{
		m_pname = pName;
	}
	//手机品牌名字
	string m_pname;
};
class person
{
public:

	person(string name, string pName) :m_name(name), m_phone(pName)
	{

	}
	
	//姓名
	string m_name;
	//手机
	Phone m_phone;
};
void text1()
{
	person p("zs","iphone13promax");
	cout << p.m_name << "拿着" << p.m_phone.m_pname << endl;
}
int main()
{
	text1();
	  
	system("pause");
	return 0;
}

运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值