从我所了解的情况来说,将整个结构传递给函数并且不通过引用的方式这样做可能会对系统资源征税。所以,我想要通过引用来处理它们。我正在创建一个具有以下结构的字符发生器:通过引用将结构数组传递给函数的问题
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。但显然,我做错了什么。任何人都可以看到问题吗?
非常感谢!我忘记了数组总是通过引用传递的。对不起,如果这是一个愚蠢的问题,我正在努力学习这些东西 –