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;
}
运行结果: