[英]How can I forward declare an array inside a namespace in c++
I've been trying to find out how I can use namespaces properly.我一直在尝试找出如何正确使用命名空间。 I want to use a namespace, but not have to define it in the header file.
我想使用命名空间,但不必在头文件中定义它。 I am not sure how I can do this with an array inside the namespace.
我不确定如何使用命名空间内的数组来做到这一点。 I either get an "already defined symbol" error, or I get told that the namespace has not been declared.
我要么收到“已定义符号”错误,要么被告知名称空间尚未声明。
I have tried to write code like this:我曾尝试编写这样的代码:
//Header.h
namespace foo {
int array[5];
}
//Source.cpp
#include "Header.h"
namespace foo {
int array[5] = {0, 1, 2, 3, 4, 5};
}
And it returns an error.它返回一个错误。
If I try to forward-declare the namespace, like I would any other variable, it says the namespace is undefined, so I'm not sure what the correct way to achieve this is.如果我尝试向前声明命名空间,就像我对任何其他变量一样,它表示命名空间未定义,所以我不确定实现这一点的正确方法是什么。
//Header.h
extern int foo::array;
//Source.cpp
#include "Header.h"
namespace foo {
int array[5] = {0, 1, 2, 3, 4, 5};
}
This这个
namespace foo {
int array[5];
}
is a definition of the array.是数组的定义。
On the other hand, this declaration另一方面,这个声明
extern int foo::array;
is present in the global namespace instead of the namespace foo
.存在于全局命名空间而不是命名空间
foo
。 That is the namespace foo
was not yet declared and you may not use the qualified name foo::array
.那是命名空间
foo
尚未声明,您不能使用限定名称foo::array
。
To declare the array in the header use the storage specifier extern
.要在标头中声明数组,请使用存储说明符
extern
。
namespace foo {
extern int array[5];
}
And then in the cpp file you can write for example然后在cpp文件中你可以写例如
int foo::array[5] = {0, 1, 2, 3, 4, 5};
Same way as in global namespace:与全局命名空间中的方式相同:
// .h
namespace foo {
extern int array[5];
}
// .cpp
namespace foo {
int array[5] = {1, 2, 3, 4, 5};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.