日期 | 变更记录 |
---|---|
2021-10-21 | 创建 |
复制构造函数
下列情况,会调用复制构造函数:
将某个对象初始化为类的另一个对象时
将对象当作参数传递给函数时
函数返回对象时
为什么用复制构造函数:
如果没有定义复制构造函数,编译器将自动生成一个
自动生成的复制构造函数只是将对象内容逐个字节的copy
当数据成员有指针时,将导致两个对象的指针指向同一个地址
赋值操作符
默认的赋值操作符只是逐个字节地将源对象复制到目标对象
赋值操作符和复制构造函数
相同点:
都是为了避免在复制过程中造成的空指针问题
都需要在函数中,明确的为每一个指针开辟新的地址
都有默认的情况
不同点:
赋值操作符用的=,是在两个已存在的对象中进行数据的复制
复制构造符是创建一个新的对象
Example
复制构造函数
将某个对象初始化为类的另一个对象时自动调用复制构造函数
#if 1
#include <iostream>
#include <string.h>
using namespace std;
class stu
{
private:
char* name;
int age;
public:
stu();
stu(const char name[], int age);
stu(const stu& s);
~stu();
void showName()
{
cout << this->name << endl;
}
};
stu::stu()
{
cout << "无参数的构造函数" << endl;
this->name = new char[20];
strcpy(name, "小明");
age = 20;
}
stu::stu(const stu& s)
{
cout << "复制构造函数" << endl;
//this->name = s.name;//浅复制
this->name = new char[20];
strcpy(this->name,s.name);
this->age = s.age;
}
stu::~stu()
{
cout << "我是析构函数" << endl;
delete[] this->name;
}
int main()
{
stu *s1 = new stu;
stu s2(*s1);//复制构造函数编译器默认会提供一个
delete s1;
return 0;
}
#endif
将对象当作参数传递给函数时自动调用复制函数
#if 1
#include <iostream>
#include <string.h>
using namespace std;
class stu
{
private:
char* name;
int age;
public:
stu();
stu(const char name[], int age);
stu(const stu& s);
~stu();
void showName()
{
cout << this->name << endl;
}
};
stu::stu()
{
cout << "无参数的构造函数" << endl;
this->name = new char[20];
strcpy(name, "小明");
age = 20;
}
stu::stu(const stu& s)
{
cout << "复制构造函数" << endl;
//this->name = s.name;//浅复制
this->name = new char[20];
strcpy(this->name,s.name);
this->age = s.age;
}
stu::~stu()
{
cout << "我是析构函数" << endl;
delete[] this->name;
}
void fun1(stu s)
{
s.showName();
}
int main()
{
stu s2;
fun1(s2);
return 0;
}
#endif
赋值操作符
#if 1
#include <iostream>
#include <string.h>
using namespace std;
class stu1 {
int* ptr;
public:
stu1() {
ptr = new int;
*ptr = 0;
}
stu1(int i)
{
ptr = new int;
*ptr = i;
}
~stu1()
{
delete ptr;
}
void show()
{
cout << *ptr << endl;
}
stu1& operator = (const stu1& s)
// 赋值操作符
{
*ptr = *(s.ptr);
return *this;
}
};
int main()
{
stu1 s1(20);
stu1 s2;
s2 = s1;
// 赋值操作
s2.show();
}
#endif