一、深拷贝和浅拷贝构造函数总结:
1、两个特殊的构造函数:
(1)无参构造函数:
没有参数的构造函数
Class Test
{
public:
Test()
{
//这是一个无参构造函数
}
};
当类中没有定义构造函数时,编译器默认提供一个无参构造函数,并且其函数体为空;换句话来说,就是我们在类中,不用我们程序猿自己写,编译就自动提供了无参构造函数(只是我们肉眼看不到!)
#include <iostream>
#include <string>
class Test{
//编译器默认给我们提供了一个无参构造函数,只是我们肉眼看不到
};
int main()
{
Test t;
return 0;
}
结果输出(编译时能够通过的):
root@txp-virtual-machine:/home/txp# g++ test.cpp
root@txp-virtual-machine:/home/txp#
(2)拷贝构造函数:
参数为const class_name&的构造函数
class Test{
public:
Test(const Test& p)
{
}
}
当类中没有定义拷贝构造函数时,编译器默认提供了一个拷贝构造函数,简单的进行成员变量的值赋值
#include <iostream>
#include <string>
class Test{
private:
int i;
int j;
public:
Test(const Test& p)编译器默认提供这样操作的
{
i = p.i;
j = p.j;
}
};
int main()
{
Test t;
return 0;
}
输出结果(编译可以通过):
root@txp-virtual-machine:/home/txp# g++ test.cpp
root@txp-virtual-machine:/home/txp#