所以我做一个小项目只是为了好玩(因为在我的课堂上,我们并没有做任何有趣的事情)试图复制旧RPG的战斗系统,我遇到了这个问题:我有2个类,一个需要来自另一个类的变量的值。我仍然有点新鲜,所以请不要把任何事情视为理所当然。这是代码:
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
class Moveset
{
int pp;
int precision;
std::string moveName;
public:
bool hit(int precision)
{
srand(time(0));
int randomNumber = rand() % 100 + 1;
if (randomNumber <= precision && randomNumber >= 1)
{
return true;
}
else
{
return false;
}
}
void scratch(float &HP)
{
pp = 15;
precision = 80;
moveName = "scratch";
bool success = hit(precision);
//here i want to replace the question marks with the playerName from
//the player class, but how can i do that?
std::cout << "??? used " << moveName << " !" << std::endl;
pp--;
if (success)
{
HP = HP - 20;
std::cout << "HP: " << HP << std::endl;
}
else
{
std::cout << "It missed!" << std::endl;
}
}
};
class Player
{
public:
float HP;
std::string playerName;
int age;
Moveset ptr0;
};
int main()
{
for (int i = 0; i <= 2; i++)
{
switch (i)
{
case 0:
std::cout << "Welcome to the test of this special combat system!" << std::endl;
break;
case 1:
std::cout << "In this small test you'll have access of a prototype of it!" << std::endl;
break;
case 2:
std::cout << "Now get ready and experience the first version ever! Go!" << std::endl;
break;
default:
break;
}
system("pause");
system("cls");
}
Moveset Move;
Player Niko;
Niko.HP = 100;
Niko.playerName = "Niko";
Niko.ptr0 = Move;
Niko.ptr0.scratch(Niko.HP);
system("pause");
}
答案 0 :(得分:1)
更好地使用对象,如下所示:
void scratch(Player &p)
因此,您将获得所有播放器数据,而不仅仅是HP。
您在Player
和Moveset
类之间存在交叉依赖关系,但这是其他问题,您还可以在Player
中保留对Moveset
的引用它拥有,或使用接口。