是否可以在C ++中从构造函数访问对象名称?

时间:2017-06-09 13:30:57

标签: c++ oop object

所以我的问题是,是否可以从构造函数访问正在构造的对象的名称。这是我的代码片段:

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我希望第一个cout语句打印出Tyler's Health is XYZ

我希望这可以工作,这样我就可以创建一个对象而不必每次都对该名称进行硬编码。

如果这是对我想要实现的目标的错误解释,我很抱歉。提前感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

在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;
}