|
本帖最后由 虚怀若谷smile 于 2021-6-25 08:42 编辑
我最近在看基础课程的视频学习,学到类的析构函数和运算符重载,看到syc老师写的相关例子,想动手试试。但是发现新建的两个对象stud_1和stud_2,在test()函数运行完成时空间释放需调用析构函数释放new出来的字符数组,发现两次进入析构函数释放的都是stu2的字符数组,所以第二次就崩溃了,这是为什么?哪里出了问题呢?程序如下
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class CStudent
{
public:
char* pname;
char sex;
int num;
int age;
public:
CStudent(char* t_pname, char t_sex, int t_num, int t_age) :sex(t_sex), num(t_num), age(t_age) //构造函数1
{
int len = strlen(t_pname) + 1;
pname = new char[len];
memset(pname, 0, len);
strcpy_s(pname, len, t_pname);
};
CStudent() {};//构造函数2
~CStudent()//析构函数
{
if (pname)
{
delete[]pname;
}
}
CStudent operator=(CStudent& stu)//等号运算符重载
{
this->age = stu.age;
this->sex = stu.sex;
this->num = stu.num;
int len = strlen(stu.pname) + 1;
this->pname = new char[len];
memset(this->pname, 0, len);
strcpy_s(pname, len, stu.pname);
return *this;
}
};
void test()
{
CStudent stud_1("zhangsan", 'f', 1001, 20);
CStudent stud_2;
stud_2 = stud_1;
}
int _tmain(int argc, _TCHAR* argv[])
{
test();
return 0;
}
因为执行这条语句的时候会产生一个临时的对象,这个临时的对象跟 stud_2 内部的pname所指向的地址是一样的,所以释放两次就会报错!
一种解决办法是添加个拷贝构造函数:
- CStudent(CStudent& stu)
- {
- this->age = stu.age;
- this->sex = stu.sex;
- this->num = stu.num;
- int len = strlen(stu.pname) + 1;
- this->pname = new char[len];
- memset(this->pname, 0, len);
- strcpy_s(pname, len, stu.pname);
- };//拷贝构造函数
复制代码
|
上一篇: vs2013 如何导出和导入所有断点?下一篇: CListCtrl::GetColumnOrderArray
|