注册 登录
编程论坛 C++教室

这段代码运行正确为什么会有debug error?

fenyujinian 发布于 2012-07-31 22:18, 378 次点击
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Student
{
public:
    Student(char * name,char * st_no,float score1);
    void show_st();//输出姓名学号和成绩
    void show_count_sum_avg();//输出总、平均成绩
    ~Student();
private:
    char * sno;
    char * sname;
    float score;
    //学生总成绩、平均成绩、人数是学生共享的数据,因此定义为静态数据成员
    static int count;
    static float sum;
    static float avg;
};
Student::Student(char * name,char * st_no,float score1)
{
   sname=new char(strlen(name)+1);
   strcpy(sname,name);
   sno=new char(strlen(st_no)+1);
   strcpy(sno,st_no);
   score=score1;
   ++count;
   sum=sum+score;
   avg=sum/count;
}
Student::~Student()
{
   delete [] sname;
   delete [] sno;
}
void Student::show_st()
{
    cout<<setw(7)<<sno;
    cout<<setw(8)<<sname;
    cout<<setw(8)<<score;
}
void Student::show_count_sum_avg()
{
      cout<<setw(8)<<sum;
      cout<<setw(10)<<avg;
      cout<<setw(8)<<count<<endl;

}
//初始化静态数组成员
int Student::count=0;
float Student::avg=0.0;
float Student::sum=0.0;


void main()
{
   cout<<"sno    "<<"sname   "<<"score   "<<"sum   "<<"avg   "<<"count   \n";
   Student st1("战三","001",90);
   st1.show_st();
   st1.show_count_sum_avg();
   Student st2("罔替","002",78);
   st2.show_st();
   st2.show_count_sum_avg();
   Student st3("丽丽","003",76);
   st3.show_st();
   st3.show_count_sum_avg();
}
2 回复
#2
rjsp2012-08-01 08:33
sname=new char(strlen(name)+1);
改为
sname=new char[strlen(name)+1];
其他类似
#3
pangding2012-08-06 11:04
楼主如果把编译时的错误信息也发上来的话,我想我们就不用看代码了。
1