gpt4 book ai didi

c++ - 如果使用嵌套命名空间,如何转发声明 C++ 结构?

转载 作者:行者123 更新时间:2023-12-04 17:01:09 25 4
gpt4 key购买 nike

我有以下 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在 A.h.您确实声明了 x::y::z::Container ,但这并没有命名相同的类型。只需将声明移至 y命名空间:

namespace y {
namespace z {

struct Container;

进入->
namespace y {

struct Container;

namespace z {

关于c++ - 如果使用嵌套命名空间,如何转发声明 C++ 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66427083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com