创建对象时为对象的成员属性赋值。
语法:
1,没有返回值,不写void
2,函数名称与类名相同
3,可以有参数,因此可以重载
类名(){}
构造函数的构造和分类
class Person
{
public:
Person() //构造函数
{
cout << "Person 无参gouzao" << endl;
}
Person(int a) //有参构造
{
age = a;
cout << "Person 有参gouzao" << endl;
}
~Person() //析构函数
{
cout << "Person xigou" << endl;
}//拷贝构造
Person(const Person &p)
{
age = p.age;
cout << "copy gouzao" << endl;
}
int age;
};void test()
{
//括号法调用构造函数
//调用默认构造时不要加(),因为加()后编译器会默认为函数声明
Person p1;
Person p2(10); //有参构造调用
Person p3(p2); //拷贝构造调用
//显示法
Person p1;
Person p2 = Person(10); //调用有参构造 person(10);匿名对象
Person p3 = Person(p2); //拷贝构造调用
//不要利用拷贝构造函数来初始化匿名对象 编译器会人会Person (p3) ===Person p3
//隐式转换法
Person p4 = 10; //调用有参构造 相当于写了Person p4 = Person (10)
Person p3 = p2; //拷贝构造调用
}
拷贝构造函数调用时机
1,使用一个已经创建好的对象来初始化新对象
2,值传递的方式给函数参数传值
3,值的方式返回局部对象
深拷贝与浅拷贝
浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
class Person
{
public:
//构造函数
Person(int age,int height)
{
m_age = age;
m_height=new int(height);
cout << "Person 有参gouzao" << endl;
}
//析构函数
~Person()
{
//将堆区开辟的数据作释放操作
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
cout << "Person xigou" << endl;
}
//自己实现拷贝构造函数,解决浅拷贝带来的问题
Person(const Person& p)
{
cout << "copy gouzao" << endl;
m_age = p.m_age;
//m_height = p.m_height; 编译器默认实现这行代码
//深拷贝操作
m_height = new int(*p.m_height);
}
int m_age;
int* m_height;
};
void test()
{
Person p1(20,160);
Person p2(p1);
cout << "p1年龄是" << p1.m_age <<"身高是"<<*p1.m_height << endl;
}
int main()
{
test();
system("pause");
return 0;
}