|
就是f5调试的时候会在断点出现第一个图片的错误,CTRL+f5却可以直接运行,
以下为代码,实在不好意思,这个好像不能直接上传工程文件吗?只能这样上传了,有点多,抱歉抱歉
#include <iostream>
using namespace std;
#include <string>
#include "Student.h"
int average(CStudent*arr_stu, int num)
{
if (!arr_stu || num <= 0)
{
return 0;
};
EstudentType stud_type = arr_stu[0].type;
int sum_age=0;
for (int idx = 0; idx < num; idx++)
{
switch (stud_type)
{
case EstudentType_Xiao:
sum_age += ((CXiaoStudent*)arr_stu)[idx].age;
break;
case EstudentType_Zhong:
sum_age += ((CZhongStudent*)arr_stu)[idx].age;
break;
default:
break;
}
}
int av_age=sum_age / num;
switch (stud_type)
{
case EstudentType_Xiao:
cout << "小学生的平均年龄是" << av_age;
break;
case EstudentType_Zhong:
cout << "中学生的平均年龄是" << av_age;
break;
default:
break;
}
return av_age;
}
int main()
{
CStudent *stud = new CStudent("ddddddddddddddd", 'm', 50, 40);
CZhongStudent arr[3];
arr[0].age = 20;
arr[1].age = 18;
arr[2].age = 25;
average(arr, 3);
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;
EstudentType type;
CStudent()
{
///
}
CStudent(char* t_name, char t_sex, int t_num, int t_age);
~CStudent();
};
class CXiaoStudent:public CStudent
{
public:
int shuxue_score;
int yuwen_score;
CXiaoStudent();
protected:
private:
};
class CZhongStudent :public CXiaoStudent
{
public:
int wuli_score;
int huaxue_score;
CZhongStudent();
};
#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);
type = EstudentType_Error;
cout << "oooo" << endl;
sex = t_sex;
num = t_num;
age = t_age;
}
CStudent::~CStudent()
{
if (p_name)
{
delete[]p_name;
}
cout << "niubi" << endl;
}
CXiaoStudent::CXiaoStudent()
{
type = EstudentType_Xiao;
}
CZhongStudent::CZhongStudent()
{
type = EstudentType_Zhong;
}
报错的原因:
CZhongStudent arr[3] 没有初始化p_name,而析构器中却直接delete []p_name
p_name 声明修改:
- class CStudent
- {
- public:
- //
- char *p_name = nullptr;
- char sex;
- int num;
- int age;
- EstudentType type;
- CStudent(){}
- CStudent(char* t_name, char t_sex, int t_num, int t_age);
- ~CStudent();
- };
复制代码
析构器修改为:
- CStudent::~CStudent()
- {
- if (nullptr != p_name)
- {
- delete[]p_name;
- p_name = nullptr;
- }
- cout << "niubi" << endl;
- }
复制代码
|
上一篇: C++ 如何不用图形库绘图?下一篇: 奇怪 为什么gcc运行结果和vc2013会不一样
|