//建立一个名为CStudent的类,该类有以下几个属性:学号、姓名(使用字符指针)、成绩,并为上述属性定义相应的方法。
//用C++ 面向对象的程序设计方法,找到并输出存放在CStudent类动态数组中学生成绩最高的学生信息(需考虑分数相同的情况,输出学号、姓名和成绩)。
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
class Cstudent
{
private:
int size;
int no[100];
char* name[10];
int score[100];
public:
Cstudent() {};
Cstudent(int sz)
{
size = sz;
*name = new char[size];
}
~Cstudent();
void set(int);
void compare();
void show();
};
inline Cstudent::~Cstudent()
{
size = 0;
delete[]no;
delete[]score;
delete[]name;
}
void Cstudent::set(int sz)
{
size = sz;
for (int i = 0; i < size; i++)
{
cin >> no[i];
cin >> * name[i] ;//这个地方不知道为什么调试的时候错了
cin >> score[i];
}
}
void Cstudent::compare()
{
int t;
char sss;
for (int i = 1; i < size; i++)
{
for (int j = 0; j < size-i; j++)
{
if (score[j]<score[j+1])
{
t = score[j];
score[j] = score[j + 1];
score[j + 1] = t;
t = no[j];
no[j] = no[j + 1];
no[j + 1] = t;
sss = *(*name + j);
*(*name + j)= *(*name + j+1);
*(*name + j + 1) = sss;
}
if (score[j] == score[j + 1])
{
if (*(*name + j) < * (*name + j + 1))
{
t = score[j];
score[j] = score[j + 1];
score[j + 1] = t;
t = no[j];
no[j] = no[j + 1];
no[j + 1] = t;
sss = *(*name + j);
*(*name + j) = *(*name + j + 1);
*(*name + j + 1) = sss;
}
}
}
}
}
void Cstudent::show()
{
cout << "NO." << no[0] << " 姓名:" << *(*name) << " 成绩:" << score[0] << endl;
}
int main()
{
Cstudent s1;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
s1.set(n);
}
s1.compare();
s1.show();
return 0;
}
程序没有错误,但不能运行,用的vs,希望有人能解答。
你这个类设计的不太正确,Cstudent该有三个个属性:学号、姓名(使用字符指针)、成绩
至于学生的数目,不应该是Cstudent类的属性,而是应该创建多少个Cstudent对象
而且你的析构函数是不是也写错了,no和score没有分配内存,为什么要delete
我改了一下,你看看
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
class Cstudent
{
private:
int no;
char* name;
int score;
public:
Cstudent() {};
Cstudent(int _no, char* _name, int _score){
no = _no;
name = _name;
score = _score;
}
int getScore() { return score; }
~Cstudent() = default;
void show();
};
void Cstudent::show()
{
cout << "NO." << no << " 姓名:" << name << " 成绩:" << score << endl;
}
int main()
{
int n;
cin >> n;
vector<Cstudent*> vcs;
for (int i = 0; i < n; i++){
int no, score;
char* name = new char[256];
cin >> no;
cin >> name;
cin >> score;
Cstudent* tmp = new Cstudent(no, name, score);
vcs.push_back(tmp);
}
for (auto s : vcs) {
s->show();
}
sort(vcs.begin(), vcs.end(), [](Cstudent*& cs1, Cstudent*& cs2) {return cs1->getScore() >= cs2->getScore();});
auto beg = vcs.begin();
(*beg)->show();
return 0;
}
name 这个没有分配空间就操作了