名称空间问题

Namespace problems

本文关键字:问题 空间      更新时间:2023-10-16

所以我得到以下错误:

..Actor.h:35: error: `Attack' is not a member of `RadiantFlux'
..Actor.h:35: error: template argument 1 is invalid
..Actor.h:35: error: template argument 2 is invalid
..Actor.h:35: error: ISO C++ forbids declaration of `attacks' with no type

这一行(除其他行外):

std::vector<RadiantFlux::Attack> attacks;

相关文件如下:

Actor.h:

#ifndef ACTOR_H_
#define ACTOR_H_
#include <string>
#include <vector>
#include "Attack.h"
namespace RadiantFlux {
...
class Actor {
private:
    std::string name;
    int health;
    std::vector<RadiantFlux::Attack> attacks;
    Attributes attributes;
public:
    ...
};
}
#endif /* ACTOR_H_ */

Attack.h:

#ifndef ATTACK_H_
#define ATTACK_H_
#include <string>
#include <stdlib.h>
#include <time.h>
#include "Actor.h"
namespace RadiantFlux {
... 
class Attack {
private:
    ...
public:
    ...
};
}
#endif /* ATTACK_H_ */

为什么我得到这些错误,我能做些什么来修复它们?我认为这与名称空间有关。

你的头文件有一个循环依赖。
Attack.h包含Actor.h,反之亦然。
使用类的前向声明来避免循环依赖问题。


鉴于OP的评论,以下是需要做的:

class Actor;
class Attack
{
};

如果你的代码编译失败后,你需要阅读链接的答案和理解为什么错误和如何解决它。链接的答案解释了这一切。

ActorAttack都相互引用,因此您需要在其中一个文件中添加前向声明。

例如,在Actor.h中:

class Attack;
class Actor
{
    ...
};