gpt4 book ai didi

c++ - 如何从 C++ 中的另一个实例访问一个实例的信息?

转载 作者:行者123 更新时间:2023-11-30 05:38:00 25 4
gpt4 key购买 nike

我刚开始学习 OOP 概念,为了帮助自己学习,我创建了一个 Characters 类。从这个类中,我创建了一个名为 main 的实例和一个名为 monster 的实例。这是该类的代码:

#include <iostream>
#include <string>

using namespace std;
class Character {

public:
string name;
float health;
int attackLevel;
int defenseLevel;

void setAttr(string sName,float sHealth, int sAttackLevel, int sDefenseLevel) {
name = sName;
health = sHealth;
attackLevel = sAttackLevel;
defenseLevel = sDefenseLevel;

}



void attack(int whatInstanceToAttack) {

whatInstanceToAttack.hitpoints -= 20; //obviously not valid but how do i do this?

return whatInstanceToAttack;
}
int defend(string defend) {

int damageRelieved = defenseLevel * 2;
return damageRelieved;
}




};
int main() {
Character main;
Character monster;
main.setAttr("Rafael",200,100,30);
monster.setAttr("Monster1",30,40,30);
cout << "Default Values for Raf are;" << endl;
cout << main.name << endl;
cout << main.health<< endl;
cout << main.attackLevel << endl;
cout << main.defenseLevel << endl;


cout << "Default values for monster are" << endl;
cout <<monster.name << endl;
cout <<monster.health << endl;
cout << monster.attackLevel<< endl;
cout << monster.defenseLevel << endl;



return 0;
}

基本上我想做的是以某种方式通过主实例访问怪物实例。我想通过运行攻击方法来做到这一点。所以如果我运行

main.attack(monster);

然后我想让怪物失去 20 点生命值。

我该怎么做?

最佳答案

您只需要在攻击方法中传递 Character 的引用即可。我认为您必须了解按值传递和按引用传递概念。如果没有,您可以阅读它 here

void attack(Character &whatInstanceToAttack)  {

whatInstanceToAttack.hitpoints -= 20; //obviously not valid but how do i do this?

}

关于c++ - 如何从 C++ 中的另一个实例访问一个实例的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com