在其他类中,使用在代码中后面声明的类

Use a class that is declared after in the code, in other class

本文关键字:声明 其他 代码      更新时间:2023-10-16

也许标题不太合适。

我有两个类"播放器"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
};
相关文章: