我正在尝试创建一个名为 Player 的类,它有一个名为 scores 的数组,在 Player 类属性中声明了一个大小。然而,当我初始化一个新播放器时,sizeof(scores) 方法给了我 20,事实上,初始化一个大小为 20 而不是 5 的分数数组。我想知道为什么以及如何解决这个问题。这是代码和输出。
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
struct stats {
unsigned int min;
unsigned int max;
unsigned int mode;
unsigned int modeFreq;
unsigned int mean;
unsigned int total;
};
class Player {
public:
int scores[5];
stats pStats;
void inputScores();
void calculateStats();
void printScores();
};
void Player::printScores(){
cout << "Printing Scores..." << endl;
for (int i = 0; i < sizeof(scores); i++) {
cout << scores[i] << endl;
}
}
void Player::inputScores(){
for (int i = 0; i < sizeof(scores); i++) {
cout << "Enter a score for [" << i << "]: ";
int input;
cin >> input;
scores[i] = input;
}
}
int main() {
Player p;
cout << sizeof(p.scores);
p.inputScores();
p.printScores();
}
这给了我这个:
20
Enter a score for [0]: 1
Enter a score for [1]: 2
Enter a score for [2]: 3
Enter a score for [3]: 4
Enter a score for [4]: 5
Enter a score for [5]: 6
Enter a score for [6]: 7
Enter a score for [7]: 8
Enter a score for [8]: 20
Enter a score for [0]: 1
Enter a score for [1]: 2
Enter a score for [2]: 3
Enter a score for [3]: 4
Enter a score for [4]: 5
Enter a score for [5]: 6
Enter a score for [6]: 7
Enter a score for [7]: 8
Enter a score for [8]:
....
以此类推,最多20...