我剛剛開始學習OOP概念並幫助自己學習,我創建了一個Characters類。從這門課我做了一個叫做main的實例和一個叫做monster的實例。這裏是該類的代碼:如何從C++中的另一個實例訪問實例中的信息?
#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'函數返回一個'int'值,因爲'attack'已被聲明爲'void'函數(即它沒有返回值),所以這將不起作用。有一些關於函數參數和返回類型的閱讀[這裏](http://www.cplusplus.com/doc/tutorial/functions/)可能會有所幫助。 – Laserbreath