ADA*_* GD 1 c++ class declaration header-files
我想创建带有参数的方法,该参数链接到Enemy稍后声明的参数。\n这是我的代码:
#include <iostream>\n#include <vector>\nusing namespace std;\nclass Weapon{\n public:\n int atk_points;\n string name;\n string description;\n void Attack(Entity target){\n \n };\n};\nclass Armor{\n public:\n int hp_points;\n string name;\n string description;\n int block_chance;\n};\nclass Entity{\n public:\n int hp;\n int atk;\n string name;\n vector<Weapon> weapons;\n vector<Armor> armors;\n};\nRun Code Online (Sandbox Code Playgroud)\n我尝试寻找答案,但没有发现任何有用的信息。\n以下是错误日志:
\nprog.cpp:9:15: error: \xe2\x80\x98Entity\xe2\x80\x99 has not been declared\n void Attack(Entity target){\nRun Code Online (Sandbox Code Playgroud)\n
问题在于编译器不知道您用作参数类型的Entity位置是什么。所以你需要告诉编译器这Entity是一个类类型。
有两种方法可以解决这个问题,如下所示:
要解决这个问题,您需要执行以下两件事:
Entity。Attack成为引用类型,这样我们就可以避免不必要的复制参数,而且因为我们提供的是成员函数的定义而不仅仅是声明。class Entity; //this is the forward declaration
class Weapon{
public:
int atk_points;
string name;
string description;
//------------------------------v------------>target is now an lvalue reference
void Attack(const Entity& target){
};
};
Run Code Online (Sandbox Code Playgroud)
解决此问题的另一种方法是,您可以仅在类内部提供成员函数 ' 的声明Attack,然后在类的定义之后提供定义,Entity如下所示:
class Entity; //forward declaration
class Weapon{
public:
int atk_points;
string name;
string description;
//------------------------------v----------->this time using reference is optional
void Attack(const Entity& target); //this is a declaration
};
//other code here as before
class Entity{
public:
int hp;
int atk;
string name;
vector<Weapon> weapons;
vector<Armor> armors;
};
//implementation after Entity's definition
void Weapon::Attack(const Entity& target)
{
}
Run Code Online (Sandbox Code Playgroud)