1、深拷贝与浅拷贝
#include<iostream>
using namespace std;
class Person
{
public:
//构造函数
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age, int height)
{
m_Age = age;
m_Height = new int(height);
cout << "Person的有参构造函数调用" << endl;
}
拷贝构造函数
Person(const Person &p)
{
//将传入的人身上的所有属性,拷贝到我身上
m_Age = p.m_Age;
cout << "Person的拷贝构造函数调用" << endl;
m_Height = new int(*p.m_Height);
}
~Person()
{
//析构代码,将堆区开辟数据做释放操作
if (m_Height != NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "Person的构析构函数调用" << endl;
}
int m_Age;//年龄
int *m_Height;//身高
};
void test01()
{
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()
{
test01();
system("pause");
return 0;
}
2、初始化列表
#include<iostream>
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)
{
}
int m_A;
int m_B;
int m_C;
};
void test01()
{
Person p(1, 2, 3);
//Person p;
cout << "m_A= " << p.m_A << endl;
cout << "m_B= " << p.m_B << endl;
cout << "m_C= " << p.m_C << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
3、类对象作为类成员
#include<iostream>
using namespace std;
#include<string>
//类对象作为类成员
//手机类
class Phone
{
public:
Phone(string pName)
{
m_PName = pName;
cout << "Phone的构造函数调用" << endl;
}
~Phone()
{
cout << "Phone的析构函数调用" << endl;
}
//手机品牌名称
string m_PName;
};
//人类
class Person
{
public:
Person(string name, string pName) :m_Name(name), m_Phone(pName) //m_Phone = pName
{
cout << "Person的构造函数调用" << endl;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
//姓名
string m_Name;
//手机
Phone m_Phone;
};
//当其他类对象作为本类成员,构造时候先构造类对象,再构造自身
//析构函数时,自身对象先,类对象后释放
//析构和构造顺序相反
void test01()
{
Person p("张三", "苹果Max");
cout << p.m_Name << "拿着:" << p.m_Phone.m_PName << endl;
}
int main()
{
test01();
system("pause");
return 0;
}