1、用对象来初始化对象
int a = 6;
int b = a;
person p1(“zhangsan”,18,true); //person是一个class类
person p2(p1); //用p1对象来初始化p2对象
person p2 = p1; //效果等同于上面
2、为什么可以
3、拷贝构造函数
class person
{
// 访问权限
public:
// 属性
string name; // 名字
int age; // 年龄
bool male; // 性别,男为true,女为false
// int *pInt; // 只是分配了p本身的4字节内存,并没有分配p指向的空间内存
// 构造和析构
// person(){}; // 默认构造函数
// person(string myname); // 自定义构造函数
// person(string myname, int myage); // 自定义构造函数
person(string myname, int myage, bool mymale); // 自定义构造函数
// person(string myname = "aston", int myage = 33, bool mymale = false); //默认构造函数
person(const person& pn); // 拷贝构造函数
~person(); // 默认析构函数
// 方法
void eat(void);
void work(void);
void sleep(void);
void print(void);
private:
};
//自定义构造函数的实现
MAN::person::person(string myname, int myage, bool mymale):name(myname),age(myage),male(mymale)
{
// this->pInt = new int[100]; // 分配了100个元素的数组
cout << "userdefined constructor" << endl;
}
//拷贝构造函数的实现
MAN::person::person(const person& pn):name(pn.name),age(pn.age),male(pn.male)
{
/*
this->name = pn.name;
this->age = pn.age;
this->male = pn.male;
*/
cout << "copy constructor" << endl;
}
//析构函数的实现
MAN::person::~person()
{
// 默认析构函数是空的
// delete this->pInt; // 释放单个内存
// delete[] this->pInt; // 释放数组内存
cout << "userdefined destructor" << endl;
}
1、浅拷贝的缺陷
2、如何解决
3、如何深度理解浅拷贝和深拷贝
class person
{
// 访问权限
public:
// 属性
string name; // 名字
int age; // 年龄
bool male; // 性别,男为true,女为false
int *pInt; // 只是分配了p本身的4字节内存,并没有分配p指向的空间内存
// 构造和析构
// person(){}; // 默认构造函数
// person(string myname); // 自定义构造函数
// person(string myname, int myage);
person(string myname, int myage, bool mymale);
// person(string myname = "aston", int myage = 33, bool mymale = false);
person(const person& pn); // 拷贝构造函数
~person(); // 默认析构函数
// 方法
void eat(void);
void work(void);
void sleep(void);
void print(void);
private:
};
//默认构造函数
MAN::person::person(string myname, int myage, bool mymale):name(myname),age(myage),male(mymale)
//MAN::person::person(string myname, int myage, bool mymale)
{
this->pInt = new int(5);
cout << "userdefined constructor" << endl;
}
// 深拷贝构造函数
MAN::person::person(const person& pn):name(pn.name),age(pn.age),male(pn.male)
{
/*
this->name = pn.name;
this->age = pn.age;
this->male = pn.male;
*/
pInt = new int(*pn.pInt); // 深拷贝
cout << "copy constructor" << endl;
}
MAN::person::~person()
{
// 默认析构函数是空的
delete this->pInt; // 释放单个内存
// delete[] this->pInt; // 释放数组内存
cout << "userdefined destructor" << endl;
}