C++新人 一个作业题,不太明白最后错在哪里,执行的时候回触发断点 求助~

小马从不改名 2017-12-20 02:35:24
仿佛错出在析构函数上,但是不清楚具体为什么会错。希望有大神帮忙讲一下
谢谢谢谢


#include <iostream> // 包含头文件iostream
#include <cstring>
using namespace std; // 使用命名空间std
class Course
{
public:
// start
// 成员函数定义
Course();
Course(int pId, char* pName, int pHours, char* pTeacherInCharge);
void setCourse(int pId, char* pName, int pHours, char* pTeacherInCharge);
char* teacherInCharge;
~Course();
void printCourse();
// end
private:
int id;
char* name;
int hours;
};
Course::Course()
{
cout<<"Constructed without Parameters."<<endl;
}
Course::Course(int pId, char* pName, int pHours, char* pTeacherInCharge)
{
// start
// 为数据成员赋值
id = pId;
name = pName;
hours = pHours;
teacherInCharge = pTeacherInCharge;
// end
cout<<"Constructed with Parameters."<<endl;
}
void Course::setCourse(int pId, char* pName, int pHours, char* pTeacherInCharge)
{
// start
// 为数据成员赋值
id = pId;
name = pName;
hours = pHours;
teacherInCharge = pTeacherInCharge;
// end
}
Course::~Course()
{
delete[] name;
delete[] teacherInCharge;
cout<<"Deconstructed."<<endl;
}
void Course::printCourse()
{
cout<<"id: "<<id<<", "
<<"name: "<<name<<", "
<< "hours: "<<hours<<", "
<< "teacherInCharge: "<<teacherInCharge
<<endl ;
}
int main()
{
Course c[3];
c[0].setCourse(1001,"高等数学",56,"zhangsan");
c[1].setCourse(1002,"C++程序设计",64,"lisi");
c[2].setCourse(1003,"管理学基础",48,"wangwu");
Course* pCourse=new Course(1004,"数据结构",72,"zhaoliu");
c[0].printCourse();
c[1].printCourse();
c[2].printCourse();
pCourse->printCourse();
delete pCourse;
return 0;
}
...全文
628 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38267490 2018-01-18
  • 打赏
  • 举报
回复
delete错了
棉猴 2018-01-17
  • 打赏
  • 举报
回复
Course()类的构造函数中,teacherInCharge和name的指向的是字符串字面值,字符串字面值保存在文字常量区中,程序结束后由系统释放。所以不需要使用delete来手动释放
faihung 2018-01-17
  • 打赏
  • 举报
回复
没有new不需要delete,new是必须和delete一起用的
LiYanchen0721 2018-01-17
  • 打赏
  • 举报
回复
没有new为什么要delete呢?处女答
qq_35276837 2017-12-20
  • 打赏
  • 举报
回复
没有new不需要delete
paschen 2017-12-20
  • 打赏
  • 举报
回复
~Course()中不需要delete,不是new出来的主不需要delete,否则会导致程序崩溃
GGLonlyboy 2017-12-20
  • 打赏
  • 举报
回复
字符串不是堆区的空间 不需要delete
小马从不改名 2017-12-20
  • 打赏
  • 举报
回复

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧