|
为什么运行到delete的时候会出错啊 求助!!
#include <iostream>
using namespace std;
#include <string>
#include "Student.h"
int main()
{
CStudent *stud=new CStudent("ddddddddddddddd",'m',50,40);
delete stud;
return 0;
}
#pragma once
#include <string>
#include <iostream>
using namespace std;
enum EstudentType
{
EstudentType_Error,
EstudentType_Xiao,
EstudentType_Zhong
};
class CStudent
{
public:
char *p_name;
char sex;
int num;
int age;
};
#include "Student.h"
CStudent::CStudent(char* t_name,char t_sex,int t_num,int t_age)
{
int n_len = strlen(t_name);
p_name = new char(n_len + 1);
memset(p_name, 0, n_len + 1);
strcpy(p_name, t_name);
cout << "oooo" << endl;
sex = t_sex;
num = t_num;
age = t_age;
}
CStudent::~CStudent()
{
if (p_name)
{
delete[] p_name;
}
cout << "niubi" << endl;
}
本帖最后由 cpp2019 于 2021-9-10 16:10 编辑
怪我,我只是稍微瞟了一眼你的代码,只看到没有声明构造和析构,没仔细看!
你的构造函数中有错误,给你改过来了!
new的时候有[],delete时才能用delete []xx;
- #include <cstring>
- #include <iostream>
- #pragma warning(disable : 4996)
- using namespace std;
- enum EstudentType
- {
- EstudentType_Error,
- EstudentType_Xiao,
- EstudentType_Zhong
- };
- class CStudent
- {
- public:
- char *p_name = nullptr;
- char sex;
- int num;
- int age;
- public:
- CStudent(char* t_name, char t_sex, int t_num, int t_age);
- ~CStudent();
- };
- CStudent::CStudent(char* t_name, char t_sex, int t_num, int t_age)
- {
- int n_len = strlen(t_name);
- p_name = new char[n_len + 1];
- memset(p_name, 0, n_len + 1);
- strcpy(p_name, t_name);
- cout << "oooo" << endl;
- sex = t_sex;
- num = t_num;
- age = t_age;
- }
- CStudent::~CStudent()
- {
- if (p_name)
- {
- delete[] p_name;
- p_name = nullptr;
- }
- cout << "niubi" << endl;
- }
- int main()
- {
- CStudent *stud = new CStudent((char*)"ddddddddddddddd", 'm', 50, 40);
- delete stud;
- return 0;
- }
复制代码
|
上一篇: 求指点,这个vs2013的帮助文档MSDN,如何打开使用?下一篇: extern和函数类外实现求助
|