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.
在 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.