【发布时间】:2016-01-04 09:14:12
【问题描述】:
我刚刚开始学习 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 点生命值。
我该怎么做?
【问题讨论】:
-
如果您不将
int而是Character&(对字符的引用)传递给attack,它应该会更好。 -
只是注意到你试图让你的
attack函数返回一个int值,因为attack已被声明为void函数(即它没有'不返回值)。有一些关于函数参数和返回类型here 的阅读可能会有所帮助。