0
我想創建一個名爲Player的類,它有一個名爲scores的數組,在Player類屬性中聲明瞭一個大小。然而,當我初始化一個新玩家時,sizeof(分數)方法給了我20,事實上,它確實初始化了一個大小爲20而不是5的得分數組。我想知道爲什麼以及如何解決這個問題。這裏是代碼和輸出。在類中初始化時奇怪和不正確的C++中的數組大小行爲
#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 ...
或者,使用'std :: array',它有'size'成員函數。 :-) – templatetypedef
我感謝你的建議。爲了簡單起見,我簡單地用「(sizeof(scores)/ sizeof(* scores)」替換了所有「sizeof(scores)」的事件,這很好地起作用。 –