【发布时间】:2018-08-26 23:32:39
【问题描述】:
问题:
您使用什么语法让同一类的两个对象在各自的函数中相互交互?
我在班级士兵中有两个对象。类函数attack(y) 获取一个对象的current_hp int 并减去另一个对象的atk int 值。我无法通过这样的参数传递对象名称。显然它不起作用,代码中进一步的引用也不起作用。
背景:
我一直在学习在线课程,遇到了一个应该适合我所学课程的挑战。我做到了没有问题,但我回去重写了它,牢记函数和类。
我在任何地方都找不到可以帮助我的信息,所以我来到了这里。我可能正在寻找错误的东西,但是......对此新手任何帮助将不胜感激。
class soldier{
private:
int curent_hp = 0;
int atk = 0;
int init = 0;
public:
bool attacked_yet = false;
void create_soldier(){
curent_hp = rand() % 20 + 1;
atk = rand() % 5 + 1;
init = rand() % 100 + 1;
}
int attack(y){
// the y here being the one that is being attacked
int attackroll = rand() % 100 + 1;
if (attackroll < 30){
y.curent_hp = y.curent_hp - atk;
}
}
};
【问题讨论】:
-
soldier& y,也可以考虑将其作为构造函数来代替 create_soldier。