最近在我的C++類中,我們已經瞭解了指針和類。類指針單元化局部變量
我正在嘗試製作一個有class Student
的程序,我們將指出每個學生的姓名和考試分數。
輸入姓名和考試分數後,他們被排序,然後按照從高到低的順序排列。
我相信我所有的語法都是正確的,但是我仍然在學習。我遇到的問題是,我第一次使用我的類,我得到一個未初始化的局部變量錯誤,有關如何解決此問題的任何幫助?由於存取什麼都不做,
struct Student {
double score;
std::string name;
};
:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
class Student {
private:
double score;
string name;
public:
void setScore(double a) {
score = a;
}
double getScore() {
return score;
}
void setName(string b) {
name = b;
}
string getName() {
return name;
}
};
void sorting(Student*, int);
int main()
{
Student *students;
string name;
int score;
int *count;
count = new int;
cout << "How many students? ";
cin >> *count;
while (*count <= 0) {
cout << "ERROR: The number of students must be greater than 0.\n";
cin >> *count;
}
for (int i = 0; i < *count; i++) {
cout << "Please enter the students name: ";
cin >> name;
students[i].setName(name);
cout << "Please enter " << students[i].getName() << "'s score: ";
cin >> score;
while (score < 0) {
cout << "ERROR: Score must be a positive number.\n";
cin >> score;
}
students[i].setScore(score);
}
sorting(students, *count);
for (int i = 0; i < *count; i++) {
cout << students[i].getName() << ": " << students[i].getScore() << endl;
}
system("PAUSE");
return 0;
}
void sorting(Student *s, int size) {
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (s[j].getScore() > s[(j + 1)].getScore()) {
int tmp = s[(j + 1)].getScore();
s[(j + 1)].setScore(s[j].getScore());
s[j].setScore(tmp);
string tmp1 = s[(j + 1)].getName();
s[(j + 1)].setName(s[j].getName());
s[j].setName(tmp1);
}
}
}
}
你的學生是指向學生的指針。使用'students = new Student [count];'知道'count'後,將其設爲數組。 –
有沒有必要做'count = new int;'只需將它聲明爲'int count'; – Sean
'count = new int;' - 如果您編寫這樣的代碼,您或您的老師已經超出指針要求。另外,他們沒有教'刪除'? – PaulMcKenzie