2011-11-15 274 views
5

所以,我收到以下错误:命名空间的问题

..\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_ */ 

为什么我会收到这些错误,我该如何解决这些错误?我假设它是与命名空间...

回答

12

你有你的头文件的循环依赖。
Attack.h包括Actor.h,反之亦然。
类的使用Forward Declaration避免循环依赖的问题。


由于OP的评论,这里是需要做什么:

class Actor; 

class Attack 
{ 

}; 

如果你的代码没有这样做之后编译,你需要阅读链接的答案,了解为什么错误以及如何解决它。链接的答案解释了这一切。

+0

如果我这样做,我得到一个错误:” .. \ Actor.h:26:错误:向前声明'结构RadiantFlux ::攻击'” – cactusbin

+0

我不认为一个模板参数可以作为前向声明吗?我认为Actor应该在Attack中声明为forward。但是,真的,我认为可能有不同的设计方式,以便依赖性是线性的而不是循环的。 – Kevin

+0

@cactusbin:你需要为'Attack'转发声明'Actor',而不是反过来(为什么你需要这种依赖呢?)。 –

0

0123'和Attack这两个类都是相互引用的,所以您需要在其中一个文件中添加前向声明。

例如,在Actor.h:

class Attack; 

class Actor 
{ 
    ... 
}; 
+2

不,你不能转发declare Attack,因为'std :: vector'不能用不完整的类型实例化。 –