VC驿站

 找回密码
 加入驿站

QQ登录

只需一步,快速开始

搜索
查看: 400|回复: 1

运算符重载

[复制链接]
61_avatar_middle
最佳答案
0 
在线会员 发表于 2020-8-11 13:11:42 | 显示全部楼层 |阅读模式
本帖最后由 gkz525 于 2020-8-11 13:11 编辑

第38课运算符重载,我按照视频上的操作,对运算符=进行了重载。但在delete时报错了。

头文件:

  1. <p>#pragma once
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;</p><p>class CStudent
  5. {
  6. public:
  7. char* p_name;
  8. char sex;
  9. int num;
  10. 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();
  11. };</p>
复制代码
定义文件:

  1. <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)
  2. {
  3. int n_len = strlen(t_name);
  4. p_name = new char[n_len + 1]; //+1是为了存字符串的 \0
  5. memset(p_name, 0, n_len + 1);   //清零</p><p> strcpy(p_name, t_name);</p><p>}</p><p><p>
  6. CStudent& CStudent::operator=(const CStudent& stud)
  7. {
  8. sex = stud.sex;
  9. num = stud.num;
  10. age = stud.age;  //把好复制的先复制了</p><p> //不好复制的先name这样处理
  11. if (p_name)
  12. {
  13.   delete[] p_name; //如果p_name里面之前有内容,就先把他删除掉。
  14.   p_name = NULL; //把p_name清零
  15. }</p><p> int name_len = strlen(stud.p_name) + 1; //求字符串的长度,+1是为了保存结尾的\0.
  16. p_name = new char[name_len];  // 给p_name申请空间,字符串有多长就申请多长的空间
  17. memset(p_name, 0, name_len);  // 申请完空间后要进行清零。
  18. strcpy(p_name, stud.p_name);  //清零后就可以把参数stud里面的p_name拷贝到对象里面的p_name里了。</p><p>
  19. return *this;
  20. }</p><p>CStudent::~CStudent()
  21. {
  22. if (p_name) // 如果p_name不为NULL就释放,p_name说明传入东西才执行。
  23. {
  24.   delete[] p_name;
  25. }
  26. cout << "CStudent::~CStudent()" << endl;
  27. }</p>
复制代码
main函数:

  1. <p>#include <iostream>
  2. #include <string>
  3. using namespace std;
  4. #include "Student.h"</p><p><p>
  5. class CStudent;</p><p>void test()
  6. {
  7. CStudent stud_1("zhangsan", 'f', 1001, 20);
  8. CStudent stud_2;
  9. stud_2 = stud_1;
  10. }</p><p>
  11. int main()
  12. {
  13. test();

  14. return 0;
  15. }</p>
复制代码
F11调试的时候,在如下这里报错了。
if (p_name)
{
  delete[] p_name; //如果p_name里面之前有内容,就先把他删除掉。
  p_name = NULL; //把p_name清零
}
错误类型如图:
运算符重载



请各位帮忙看看,该怎么解决?
















上一篇:求助,38课运算符重载这里
下一篇:析构函数delete指针的问题
61_avatar_middle
最佳答案
0 
ico_lz  楼主| 发表于 2020-8-11 16:10:59 | 显示全部楼层
通过自己的努力终于解决了,谢谢各位。
您需要登录后才可以回帖 登录 | 加入驿站 qq_login

本版积分规则

×【发帖 友情提示】
1、请回复有意义的内容,请勿恶意灌水;
2、纯数字、字母、表情等无意义的内容系统将自动删除;
3、若正常回复后帖子被自动删除,为系统误删的情况,请重新回复其他正常内容或等待管理员审核通过后会自动发布;
4、感谢您对VC驿站一如既往的支持,谢谢合作!

关闭

站长提醒上一条 /2 下一条

QQ|小黑屋|手机版|VC驿站 ( 辽ICP备09019393号-4 )|网站地图wx_jqr

GMT+8, 2023-6-4 18:35

Powered by CcTry.CoM

© 2009-2021 cctry.com

快速回复 返回顶部 返回列表