c++ 基础知识-类和对象-对象特性-构造函数和析构函数
1.构造函数和析构函数初始化及分类
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<<endl;
}
Person(int a)
{
m_age = a;
cout<<"Person:有参数构造函数"<<endl;
}
Person(Person &p)
{
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<<endl;
}
~Person()
{
cout<<"age :"<<m_age<<"Person:析构函数"<<endl;
}
private:
int m_age;
};
void fun()
{
Person p4;
cout<<"默认构造函数结束"<<endl;
Person p5 = Person(5);
cout<<"有参数构造函数结束"<<endl;
Person p6 = Person(p5);
cout<<"拷贝构造函数结束"<<endl;
Person(10);
cout<<"匿名对象结束"<<endl;
}
int main()
{
fun();
return 0;
}
2.拷贝构造函数调用时机
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<<endl;
}
Person(int a)
{
m_age = a;
cout<<"Person:有参数构造函数"<<endl;
}
Person(const Person &p)
{
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<<endl;
}
~Person()
{
cout<<"age :"<<m_age<<" Person:析构函数"<<endl;
}
private:
int m_age;
};
void fun()
{
Person p1(20);
Person p2(p1);
}
void fun01(Person p)
{
}
Person fun02()
{
Person p1;
cout<<"fun02 : Person p1"<<endl;
return p1;
}
int main()
{
fun02();
return 0;
}
3.构造函数调用规则
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<<endl;
}
Person(int a)
{
m_age = a;
cout<<"Person:有参数构造函数"<<endl;
}
Person(const Person &p)
{
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<<endl;
}
~Person()
{
cout<<"age :"<<m_age<<" Person:析构函数"<<endl;
}
int m_age;
};
void test01()
{
Person p1;
p1.m_age = 18;
Person p2(p1);
cout<<"p2的年龄为: "<<p2.m_age<<endl;
}
int main()
{
test01();
return 0;
}
4.深拷贝与浅拷贝
浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
浅拷贝带来的问题就是堆区内存的重复释放
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person()
{
cout<<"Person:默认构造函数"<<endl;
}
Person(int a,int height)
{
m_age = a;
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()
{
cout<<"age :"<<m_age<<" Person:析构函数"<<endl;
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
}
int m_age;
int *m_height;
};
void test01()
{
Person p1(18,189);
cout<<"p1的年龄为: "<<p1.m_age<<endl;
Person p2(p1);
cout<<"p2的年龄为: "<<p2.m_age<<endl;
}
int main()
{
test01();
return 0;
}