c++ - 如果使用嵌套命名空间,如何转发声明 C++ 结构?
问题描述
我有以下 C++ 代码
啊
namespace x {
namespace y {
namespace z {
struct Container;
class A
{
public:
A(Container& _container);
void info();
private:
Container& container;
};
}
}
}
A.cpp
#include "A.h"
#include <iostream>
namespace x {
namespace y {
namespace z {
A::A(Container& _container) : container(_container) {}
void A::info() {
std::cout << "Instance of A!" << std::endl;
}
}
}
}
容器.h
#include "A.h"
namespace x {
namespace y {
namespace z {
struct Container {
Container(): a(*this) {}
A a;
};
}
}
}
主文件
#include <cstdlib>
#include "Container.h"
int main(int argc, char** argv) {
x::y::z::Container container;
container.a.info();
return 0;
}
上面提到的代码是可编译和可工作的。
但是,假设我将它Container.h
移出z
namespace
并让它进入y
namespace
(嵌套在 中x
namespace
)。所以代码看起来像这样
啊
namespace x {
namespace y {
namespace z {
struct Container;
class A
{
public:
A(x::y::Container& _container);
void info();
private:
x::y::Container& container;
};
}
}
}
A.cpp
#include "A.h"
#include <iostream>
namespace x {
namespace y {
namespace z {
A::A(x::y::Container& _container) : container(_container) {}
void A::info() {
std::cout << "Instance of A!" << std::endl;
}
}
}
}
容器.h
#include "A.h"
namespace x {
namespace y {
struct Container {
Container(): a(*this) {}
x::y::z::A a;
};
}
}
主文件
#include <cstdlib>
#include "Container.h"
int main(int argc, char** argv) {
x::y::Container container;
container.a.info();
return 0;
}
在这种情况下,编译失败并显示以下错误消息:
In file included from A.cpp:7:
A.h:26:22: error: expected ')' before '&' token
26 | A(x::y::Container& _container);
| ~ ^
| )
A.h:31:11: error: 'Container' in namespace 'x::y' does not name a type
31 | x::y::Container& container;
| ^~~~~~~~~
A.cpp:14:5: error: expected constructor, destructor, or type conversion before '(' token
14 | A::A(x::y::Container& _container) : container(_container)
| ^
谁能告诉我为什么会弹出这些错误消息,以防我Container.h
从 中移动z
namespace
并让它y
namespace
嵌套在 中x
namespace
?
解决方案
问题是您从未x::y::Container
在 Ah You 中声明过 declare x::y::z::Container
,但这并没有命名相同的类型。只需将声明移动到y
命名空间中:
namespace y { namespace z { struct Container;
进入->
namespace y {
struct Container;
namespace z {
推荐阅读
- c# - BlackJack 卡组的单元测试
- javascript - 当按钮调用触发函数时,我的 appScript 不会生成我的 TimeBased autoSendMail 触发器
- php - 用laravel自动替换字符串中的变量
- spring - 如何在 Spring AOP 的切入点表达式中将基本包作为变量传递?
- android - USB 麦克风和设备的扬声器可以同时工作吗?
- java - 使用 openjdk 13.0.2 运行时,运行 .jar 文件会引发异常
- javascript - AngularJS ($http GET): $scope.names 始终是一个空数组,但调用后端是可以的
- oauth-2.0 - 如何使用 Azure Functions 强制执行 AAD 应用程序角色授权?
- react-native - 使用 Jest 和酶测试 React Native 中的按钮单击
- mysql - 在 pythonanywhere 中将 sql 文件导入 MySQL