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

老师布置的作业,可是在输入数据后系统崩了?求解。谢谢

过五矿 发布于 2016-03-15 22:32, 2899 次点击
#include <iostream>
#include <string.h>

using namespace std;
class Teacher;
class Student{
public:
    friend class Teacher;
    Student(char *,int);
    ~Student(){}
private:
    char * m_pName;
    int m_iScore;

};

Student::Student(char *name,int score)
{

    m_pName=new char[strlen(name)+1];
    strcpy(m_pName,name);
    m_iScore=score;
}

class Teacher{
public:
    Teacher(int MAXSIZE)
    {
     m_pStu=new Student*[MAXSIZE];
   }
    ~Teacher()
    {
        delete []m_pStu ;
        m_pStu=NULL;
    }
    void Insert(int);
    void Sort(int);
    void InfoPrint(int);
private:
    Student **m_pStu;
};


void Teacher::Insert(int MAXSIZE)
{
    char *name;
    float score;
    for(int i=0;i<MAXSIZE;i++)
    {
    cout<<"please input the information of the new student";
    cin>>name;
    cin>>score;
    Student *newStu=new Student(name,score);
    m_pStu=&newStu;
    m_pStu=m_pStu+1;
    }

}

void Teacher::Sort(int MAXSIZE)
{
    Student **temp1,**temp2,**temp;
   for(int i=0 ; i<MAXSIZE-1 ;i++)
    for(int j=0; j<MAXSIZE-1-i; j++)
   {
       if( (*(m_pStu+i))->m_iScore > (*(m_pStu+i+1))->m_iScore )
       {
           temp1=m_pStu+i;
           temp2=m_pStu+i+1;
           temp=temp1;
           temp1=temp2;
           temp2=temp;

       }
   }
}
void Teacher::InfoPrint(int MAXSIZE)
{
    for(int i=0;i<MAXSIZE;i++)
    {

        cout<<i<<" Name:"<<(m_pStu[i]->m_pName)<<endl;
        cout<<i<<" Score:"+(*(m_pStu+i))->m_iScore<<endl;
        cout<<endl;
    }
}
int main()
{
    int MAXSIZE;
    cout << "Please input the student's number" << endl;
    cin>>MAXSIZE;

    Teacher teacher(MAXSIZE);
    teacher.Insert(MAXSIZE);
    teacher.Sort(MAXSIZE);
    teacher.InfoPrint(MAXSIZE);
    return 0;
}
[code][/
只有本站会员才能查看附件,请 登录
code]
7 回复
#2
azzbcc2016-03-16 09:58
[09:58:25 azzbcc@XJH-PC src]$ g++ -W -Wall -O2 CPP.cpp

CPP.cpp: In member function ‘void Teacher::Insert(int)’:
CPP.cpp:54:20: warning: ‘name’ may be used uninitialized in this function [-Wmaybe-uninitialized]
         cin >> name;
                    ^
#3
仰望星空的2016-03-16 14:56
    Student *newStu=new Student(name,score);
这句开辟指针,然后没有释放的原因?
#4
yangfrancis2016-03-16 15:53
void Teacher::Insert(int MAXSIZE)
{
    char *name;
    float score;
    for(int i=0;i<MAXSIZE;i++)
    {
    cout<<"please input the information of the new student";
    cin>>name;
    cin>>score;
    Student *newStu=new Student(name,score);
    m_pStu=&newStu;
    m_pStu=m_pStu+1;
    }

}
这个for循环的最后两句是想做什么?感觉有点莫明其妙。
#5
过五矿2016-03-16 18:55
回复 4楼 yangfrancis
就是把每一个新开辟的对象储存到teacher中得**pstu中。
#6
过五矿2016-03-16 19:02
回复 3楼 仰望星空的
我试了释放掉内存,程序还是崩了
#7
过五矿2016-03-16 19:03
回复 4楼 yangfrancis
老师不让用继承,只能用友元类,所以设置了一个双重指针来储存学生的地址,实现管理
#8
过五矿2016-03-16 19:40
我知道为什么崩了,因为name没有分配空间,所以局部变量用完就释放掉了。谢谢大家
1