我有一个类。我的代码编译正确,但是当我试图从键盘输入这个数组时我的程序停止工作。我认为问题出在内存分配上。如何正确分配内存来解决这个问题?
class group
{
protected:
diplomStudent *arr;
int size;
public:
group(int studs)
{
arr=new diplomStudent[studs];
size=studs;
}
void setgroup()
{
for(int i=0;i<size;i++)
cin>>arr[i];//'>>' is overloaded for diplomstudent
}
}
重载操作;
friend istream& operator>>(istream& is, diplomStudent& obj)
{
is >> obj.surname;
is >> obj.name;
is >> obj.patr;
is >> obj.course;
is >> obj.rate;
is >> obj.diplom;
is >> obj.perscent;
return is;
}
主要功能:
int main()
{
group g1(2);
g1.setgroup();
return 0;
}
答案 0 :(得分:1)
问题必须在类diplomStudent的定义中,但由于您不提供该信息,我们无法确定。我正在为班级的所有成员使用一个字符串,对我来说工作得很好,这里有示例代码:
#include <iostream>
#include <string>
using namespace std;
class diplomStudent
{
public:
string surname, name, patr, course, rate, diplom, perscent;
friend istream& operator>>(istream& is, diplomStudent& obj)
{
is >> obj.surname; is >> obj.name; is >> obj.patr; is >> obj.course;
is >> obj.rate; is >> obj.diplom; is >> obj.perscent;
return is;
}
};
class group
{
protected:
diplomStudent *arr;
int size;
public:
group(int studs) : arr(new diplomStudent[studs]), size(studs) {}
~group() { delete[] arr; }
void setGroup()
{
for (int i = 0; i < size; ++i)
cin >> arr[i]; //'>>' is overloaded for diplomStudent
}
void printGroup()
{
for (int i = 0; i < size; ++i)
cout << arr[i].surname << " " << arr[i].name << " " << arr[i].patr << " " << arr[i].course
<< " " << arr[i].rate << " " << arr[i].diplom << " " << arr[i].perscent << endl;
}
};
int main()
{
group g1(2);
g1.setGroup();
g1.printGroup();
return 0;
}