在其他类中,使用在代码中后面声明的类
Use a class that is declared after in the code, in other class
也许标题不太合适。
我有两个类"播放器"answers"升级"
- 升级前已声明玩家
但我需要Player类中的一个方法,该方法使用指向升级类的指针
如果我试图编译它,我会得到尚未声明的"Upgrade"。我给出了一个示例代码。注意,我不能只切换两个类的位置,因为Upgrade也有一些方法具有指向播放器的指针
class Player{
string Name;
getUpgrade(Upgrade *); // It's a prototype
};
class Upgrade{
double Upgradeusec;
somePlayerData(Player *); // It's a prototype
};
PD:我已经搜索了大约1个小时,没有结果。
注意:这只是一个示例代码,因为实际代码的很大
您需要在定义Player类之前转发声明Upgrade;例如
class Upgrade;
class Player { ... };
class Upgrade { ... };
当然,这意味着两个类之间存在非常紧密的耦合,根据具体情况,这种耦合可能是不可取的。
您可以转发声明它。
在具有Player类代码的文件中,只需在所有#includes
和#defines
之后的顶部添加以下行
class Upgrade;
class Player
{
//the definition of the Player class
}
编译器将遵守此正向声明,并将毫无怨言地继续执行。
什么是c++中的正向声明?
只需在代码中添加一个正向声明:
class Upgrade; //forward declaration
class Player{
string Name;
getUpgrade(Upgrade *); // It's a prototype
};
class Upgrade{
double Upgradeusec;
somePlayerData(Player *); // It's a prototype
}
您需要正向声明。http://en.wikipedia.org/wiki/Forward_declarationC++有很多复杂的规则需要具体说明何时可以使用不完全类型。
class Upgrade; //<<<< add this line.
Class Player{
string Name;
getUpgrade(Upgrade); // It's a prototype
};
Class Upgrade{
double Upgradeusec;
somePlayerData(Player); // It's a prototype
};
相关文章:
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 如何制作 cmakelists.txt编译使用在其他地方声明和实现的函数和类的 CPP
- 为什么在某些编译器中可以声明像int myarr[noconstant]这样的数组;而不是在其他编译器中?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 我如何在一个 if 语句中声明所有数字我尝试通过其他方式声明所有数字,如果一个接一个,但似乎代码有逻辑错误
- 无法转发声明C typedef结构-正在查找其他建议
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- fprintf 不打印到文件,当文件指针在其他地方声明时
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 如何将char数组声明为函数参数?或告诉我此代码中还有其他问题?
- C++,字符串声明中的其他字符
- 如何使 extern 方法在共享库中定义,但使用 cmake 在其他目标中声明?
- std::d eclare_if 或其他在编译时丢弃成员声明的假设方法
- 我不允许更改变量的声明,我可以编辑哪些其他方法
- C const在函数声明中以及其他任何地方的anmpersand的右侧
- 实现文件只能识别其他类的远期声明
- 为什么在其他函数中声明的函数不参与参数相关查找?
- 向前声明C++中的其他嵌套结构
- 用于声明其他类中的对象时发生模板化类链接错误