C++ 编译错误和命名空间
这是出现错误的整个代码:
Engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include "DXManager.h"
namespace XEngine
{
class Engine
{
};
}
#endif
DXManager.h
#ifndef DX_MANAGER_H
#define DX_MANAGER_H
namespace XEngine
{
class Engine; // forward declaration
class DXManager
{
public:
void run(Engine *engine);
};
}
#endif
DXManager.cpp
#include <iostream>
#include "Engine.h"
#include "DXManager.h"
using namespace XEngine;
void DXManager::run(Engine *engine)
{
std::cout<<"DXManager::run"<<std::endl;
}
通过这 30 行代码,我得到了 20 行错误如:
'XEngine' : a namespace with this name does not exist
'XEngine' : a symbol with this name already exists and therefore this name cannot be used as a namespace name
syntax error : identifier 'Engine'
显然,我在这里遗漏了一些重要的东西。我做错了什么?
注意:我知道循环依赖是一件坏事,但在我的特定情况下,我相信它是相关的。
Here's the whole code getting the errors:
Engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include "DXManager.h"
namespace XEngine
{
class Engine
{
};
}
#endif
DXManager.h
#ifndef DX_MANAGER_H
#define DX_MANAGER_H
namespace XEngine
{
class Engine; // forward declaration
class DXManager
{
public:
void run(Engine *engine);
};
}
#endif
DXManager.cpp
#include <iostream>
#include "Engine.h"
#include "DXManager.h"
using namespace XEngine;
void DXManager::run(Engine *engine)
{
std::cout<<"DXManager::run"<<std::endl;
}
With these 30 lines of code, I'm getting 20 errors like:
'XEngine' : a namespace with this name does not exist
'XEngine' : a symbol with this name already exists and therefore this name cannot be used as a namespace name
syntax error : identifier 'Engine'
Clearly, I'm missing something important here. What am I doing wrong?
note: I am aware that circular dependency is a bad thing, but in my particular case I believe that it is relevant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 DXManager.cpp 中,您不仅仅使用命名空间 XEngine 中的一些名称。您在该命名空间中定义该函数。
所以一定是:
DXManager.cpp
AFAIK 一些编译器(如 MSVC)也处理
using
变体。但这是不正确的,因为您的语法尝试定义函数
::DXManager::run
- 而不是您想要定义的::XEngine::DXManager::run
。In DXManager.cpp you are not just using some names from namespace XEngine. You define the function in that namespace.
So must be:
DXManager.cpp
AFAIK some of the compilers (like MSVC) process
using
variant too.But it is not correct because your syntax tries to define function
::DXManager::run
- not::XEngine::DXManager::run
you intend to define.在类
Engine
的前向声明中,命名空间XEngine
此时不存在。解决方法是将声明移动到命名空间块内。
In the forward-declaration of class
Engine
the namespaceXEngine
doesn't exist at this point.A workaround would be moving the declaration inside the namespace block.
当Engine.h包含DXManager.h时,后者定义了一个类XEngine::Engine,而无需先声明命名空间。
When Engine.h includes DXManager.h, the latter defines a class XEngine::Engine without declaring the namespace first.