|
本帖最后由 gkz525 于 2020-8-11 13:11 编辑
第38课运算符重载,我按照视频上的操作,对运算符=进行了重载。但在delete时报错了。
头文件:
- <p>#pragma once
- #include <iostream>
- #include <string>
- using namespace std;</p><p>class CStudent
- {
- public:
- char* p_name;
- char sex;
- int num;
- int age;</p><p> /*static int master;*/</p><p> CStudent(char* t_name, char t_sex, int t_num, int t_age);</p><p> CStudent() {};</p><p> CStudent& operator=(const CStudent& stud);</p><p> ~CStudent();
- };</p>
复制代码 定义文件:
- <p>#include "Student.h"</p><p>//int CStudent::master = 0;</p><p>CStudent::CStudent(char* t_name, char t_sex, int t_num, int t_age) :sex(t_sex), num(t_num), age(t_age)
- {
- int n_len = strlen(t_name);
- p_name = new char[n_len + 1]; //+1是为了存字符串的 \0
- memset(p_name, 0, n_len + 1); //清零</p><p> strcpy(p_name, t_name);</p><p>}</p><p><p>
- CStudent& CStudent::operator=(const CStudent& stud)
- {
- sex = stud.sex;
- num = stud.num;
- age = stud.age; //把好复制的先复制了</p><p> //不好复制的先name这样处理
- if (p_name)
- {
- delete[] p_name; //如果p_name里面之前有内容,就先把他删除掉。
- p_name = NULL; //把p_name清零
- }</p><p> int name_len = strlen(stud.p_name) + 1; //求字符串的长度,+1是为了保存结尾的\0.
- p_name = new char[name_len]; // 给p_name申请空间,字符串有多长就申请多长的空间
- memset(p_name, 0, name_len); // 申请完空间后要进行清零。
- strcpy(p_name, stud.p_name); //清零后就可以把参数stud里面的p_name拷贝到对象里面的p_name里了。</p><p>
- return *this;
- }</p><p>CStudent::~CStudent()
- {
- if (p_name) // 如果p_name不为NULL就释放,p_name说明传入东西才执行。
- {
- delete[] p_name;
- }
- cout << "CStudent::~CStudent()" << endl;
- }</p>
复制代码 main函数:
- <p>#include <iostream>
- #include <string>
- using namespace std;
- #include "Student.h"</p><p><p>
- class CStudent;</p><p>void test()
- {
- CStudent stud_1("zhangsan", 'f', 1001, 20);
- CStudent stud_2;
- stud_2 = stud_1;
- }</p><p>
- int main()
- {
- test();
-
- return 0;
- }</p>
复制代码 F11调试的时候,在如下这里报错了。
if (p_name)
{
delete[] p_name; //如果p_name里面之前有内容,就先把他删除掉。
p_name = NULL; //把p_name清零
} 错误类型如图:
请各位帮忙看看,该怎么解决?
|
上一篇: 求助,38课运算符重载这里下一篇: 析构函数delete指针的问题
|