【发布时间】:2021-03-01 17:50:42
【问题描述】:
我有以下 C++ 代码
啊.h
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;
};
}
}
}
main.cpp
#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 中)。所以代码会是这样的
啊.h
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;
};
}
}
main.cpp
#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 嵌套在namespace 中,谁能告诉我为什么会弹出这些错误消息?
【问题讨论】:
-
你在
A.h中的前向声明仍然是一个结构x::y::z::Container。尝试将其移至x::y而不是x::y::z,类似于您在Container.h中所做的移动。 -
fwiw,这是同一问题的一个最小示例:godbolt.org/z/arWE7P
-
在
A的使用点上,编译器没有看到x::y::Container的声明,只有在zx::y::z::Container内更深一层嵌套的前向声明,因此您会收到关于不的错误将Container视为一种类型。
标签: c++ nested namespaces forward-declaration