c++ 基础知识-类和对象-对象特性-构造函数和析构函数
1.构造函数和析构函数初始化及分类
#include
#include
using namespace std;
class Person
{
public:
//构造函数,可以有参数,可以重载
//创建对象可以自动调用,并且只能调用一次
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<
m_age = a;
cout<<"Person:有参数构造函数"<
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<
cout<<"age :"<
//1.括号法调用
//Person p1;//默认构造函数,注意不是 Person p();
//Person p2(5);//有参数构造函数
//Person p3(p2);//拷贝构造函数
//输出
//Person:默认构造函数
//Person:有参数构造函数
// Person:拷贝构造函数
// Person:析构函数
// Person:析构函数
// Person:析构函数
//2.显示法调用
Person p4;
cout<<"默认构造函数结束"<
fun();
return 0;
}
2.拷贝构造函数调用时机
#include
#include
using namespace std;
//c++中拷贝构造函数调用时机通常有三种情况
//1.使用一个已经创建完毕的对象来初始化一个新对象
//2.值传递的方式给函数参数传值
//3.以值方式返回局部对象
class Person
{
public:
//默认构造函数
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<
m_age = a;
cout<<"Person:有参数构造函数"<
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<
cout<<"age :"<
Person p1(20);
Person p2(p1);
}
//输出
//Person:有参数构造函数
//Person:拷贝构造函数
//age :20 Person:析构函数
//age :20 Person:析构函数
//2.值传递的方式给函数参数传值
void fun01(Person p)
{
}
//输出
//Person:默认构造函数
//Person:拷贝构造函数
//age :2 Person:析构函数
//age :2 Person:析构函数
//3.以值方式返回局部对象
Person fun02()
{
Person p1;
cout<<"fun02 : Person p1"<
//fun();
//Person p;
//fun01(p);
fun02();
return 0;
}
3.构造函数调用规则
#include
#include
using namespace std;
class Person
{
public:
//默认构造函数
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<
m_age = a;
cout<<"Person:有参数构造函数"<
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<
cout<<"age :"<
Person p1;
p1.m_age = 18;
Person p2(p1);//拷贝 - 复制
cout<<"p2的年龄为: "<
test01();
return 0;
}
4.深拷贝与浅拷贝
浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
浅拷贝带来的问题就是堆区内存的重复释放
#include
#include
using namespace std;
class Person
{
public:
//默认构造函数
Person()
{
//m_age = 2;
cout<<"Person:默认构造函数"<
m_age = a;
m_height = new int(height);
cout<<"Person:有参数构造函数"<
cout<<"Person:拷贝构造函数"<
cout<<"age :"<
delete m_height;
m_height = NULL;//防止出现
}
}
int m_age;
int *m_height;
};
void test01()
{
//Person p1;
//p1.m_age = 18;
Person p1(18,189);
cout<<"p1的年龄为: "<
test01();
return 0;
}