所以我的问题是,是否可以从构造函数访问正在构造的对象的名称。这是我的代码片段:
Monk::Monk(int stam, int agil, string spec){
stamina = stam;
agility = agil;
specialization = spec;
cout << "'s Health is " << health() << endl;
cout << "'s DPS is " << damage() << endl;
cout << "'s current specification is a " << specName() << " monk." << endl;
}
int main() {
Monk Tyler(25000, 1245, "Brewmaster");
Monk Jackson(12500, 3000, "Windwalker");
return 0;
}
因此,基本上,如果您看一下cout
构造函数末尾的函数,我希望语句以对象名称开头而无需硬编码。因此,例如,一个对象被命名为Tyler
I,我希望第一条cout
语句打印出来Tyler's Health is XYZ
。
我希望这项工作能够使我能够创建一个对象,而不必每次都对名称进行硬编码。
如果这是对我要达到的目标的不好解释,我感到抱歉。预先感谢您提供的任何帮助!
这种解释或反射在C ++中很难
最好的办法是修改类,并为每个对象指定一个属性名称:
Monk::Monk(int stam, int agil, string spec, string name){
stamina = stam;
agility = agil;
specialization = spec;
monkName = name;
cout << monkName << "'s Health is " << health() << endl;
cout << monkName << "'s DPS is " << damage() << endl;
cout << monkName << "'s current specification is a " << specName() << " monk." << endl;
}
int main() {
Monk Tyler(25000, 1245, "Brewmaster");
Monk Jackson(12500, 3000, "Windwalker");
return 0;
}
旁注,记住你可以做
Monk::Monk(int stam, int agil, string spec, string name):stamina(stam),agility (agil),specialization(spec),monkName(name){
//stamina = stam;
//agility = agil;
//specialization = spec;
//monkName = name;
cout << monkName << "'s Health is " << health() << endl;
cout << monkName << "'s DPS is " << damage() << endl;
cout << monkName << "'s current specification is a " << specName() << " monk." << endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句