【发布时间】:2017-04-29 04:49:32
【问题描述】:
我们正在讨论我学校的课程主题。我应该创建一个名为 Student 的类,我们可以使用它在动态分配的数组中保存不同的测试分数。我正在努力弄清楚为什么当我打印出这个类的特定实例的数组时,它给了我完全不正确的值。我知道我的类的 setter 函数正在设置正确的值,但是每当我将它们打印出来时,它们都是完全错误的。下面是我的代码。 main() 中被注释掉的部分只是用来测试我的 makeArray() 函数的逻辑。
#include <iostream>
using namespace std;
class Student {
private:
string name;
int id;
int* testptr;
int num;
void makeArray() {
int array[num];
testptr = &array[num];
for (int i = 0; i < num; i++) {
array[i] = 0;
}
}
public:
Student() {
setName("None");
setID(10);
num = 3;
makeArray();
}
Student(int n) {
setName("None");
setID(10);
if (n > 0)
num = n;
else
num = 3;
makeArray();
}
Student(string nm, int i, int n) {
setName(nm);
setID(i);
if (n > 0)
num = n;
else
num = 3;
makeArray();
}
void setName(string nm) {
name = nm;
}
void setID(int i) {
if (i >= 10 && i <= 99){
id = i;
}
else {
cout << "Error: Cannot set id to " << i << " for " << getName();
id = 10;
}
}
void setScore(int i, int s) {
if ((i >= 0 && i <= num) && (s >= 0 && s <= 100)) {
//Here is where I set the values for the array. They come out correct in the console.
testptr[i] = s;
cout << testptr[i] << endl;
} else {
cout << "The test " << i << " cannot be set to " << s << " for " << getName() << endl;
}
}
string getName() const {
return name;
}
int getID() const {
return id;
}
void showScore() {
//This is where I print out the values of the array. They come out incorrect here.
for (int i = 0; i < num; i++) {
cout << "Test " << i << " had a score of " << testptr[i] << endl;
}
}
void display() {
cout << "Calling the display function" << endl;
cout << "The Name: " << getName() << endl;
cout << "The ID: " << getID() << endl;
showScore();
}
~Student() {
}
};
int main() {
Student c("Joe", 40, 5);
c.setScore(0, 90);
c.setScore(1, 91);
c.setScore(2, 92);
c.setScore(3, 93);
c.setScore(4, 94);
c.display();
/**int* testpointer;
int num = 3;
int array[num];
testpointer = &array[0];
for (int i = 0; i < num; i++) {
testpointer[i] = i;
cout << testpointer[i] << endl;
}**/
}
【问题讨论】:
-
你没有动态分配你的数组。它超出了范围并导致了可怕的 UB。
-
使用一些标准的container,可能是
std::vector