從我所瞭解的情況來說,將整個結構傳遞給函數並且不通過引用的方式這樣做可能會對系統資源徵稅。所以,我想要通過引用來處理它們。我正在創建一個具有以下結構的字符發生器:通過引用將結構數組傳遞給函數的問題
struct Stats{
string name;
int level;
int HP;
int STR;
int CON;
int DEX;
int INT;
int WIS;
int CHA;};
struct Growth{
int HPperlvl;
int STRperlvl;
int CONperlvl;
int DEXperlvl;
int INTperlvl;
int WISperlvl;
int CHAperlvl;};
struct Holdstats{
Stats classstats;
Growth classgrowth;};
const int SIZE = 10;
Holdstats classlist[SIZE] = {
{ {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1} },
{ {"Wizard", 1, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1}},
{ {"Rogue", 1, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1}}
} //These are just some examples, will be filled later
Holdstats charlist[SIZE]; //Empty array to store created characters
我將在程序中使用最簡單的函數來說明我的問題。下面的函數只需顯示傳遞給它的任何結構的信息,無論結構中的哪個位置傳遞給它。該位置在程序中預先定義。我想通過引用傳遞結構和位置。
void dispinfo(const Holdstats &p, int &i) //Should be passed a position and a structure
{
cout << endl << "\tHere is the Character/Class info you requested: "
<< "\n\t----------------------------------------------"
<< "\nName:\t\t" << p[i].classstats.name << endl
<< "Level:\t\t" << p[i].classstats.level << endl
<< "Hit Points:\t\t" << p[i].classstats.HP << endl
<< "Strength:\t\t" << p[i].classstats.STR << endl
<< "Constitution\t\t" << p[i].classstats.CON << endl
<< "Dexterity\t\t" << p[i].classstats.DEX << endl
<< "Intelligence\t\t" << p[i].classstats.INT << endl
<< "Wisdom\t\t" << p[i].classstats.WIS << endl
<< "Charisma\t\t" << p[i].classstats.CHA << endl;
}
我得到的問題與p[i]
有關。我的編譯器告訴我,對於 Holdstats & p - 沒有運算符[]
匹配這些操作數。我只會在函數頭中使用一個以前定義的結構數組的名稱(「classlist」或其他),但我希望能夠將任何結構數組傳遞給該函數。
據我所知,我調用先前定義的數組的元素i。但顯然,我做錯了什麼。任何人都可以看到問題嗎?
非常感謝!我忘記了數組總是通過引用傳遞的。對不起,如果這是一個愚蠢的問題,我正在努力學習這些東西 –