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)
{
cout << "Person 拷贝构造函数调用" << endl;
m_Age = p.m_Age;
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");
}
2、初始化列表 作用: C++ 提供了初始化列表语法,用来初始化属性。 语法:构造函数():属性(值1),属性(值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(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()
{
test01();
system("pause");
}
|