c++ - 如何使用“使用命名空间”在命名空间中定义变量?
问题描述
所以我有一个名称空间thing
,其中包含extern int
在标头中声明的变量。我试图在 .cpp 中定义它们using namespace thing;
以简化初始化,但在尝试在 .cpp 中定义变量时,它似乎不像我预期的那样工作thing.cpp
。是什么赋予了?
主.cpp:
#include <cstdio>
#include "thing.hpp"
int main()
{
printf("%d\n%d\n",thing::a,thing::func());
printf("Zero initialized array:\n");
for(int i = 0; i < 10; i++)
printf("%d",thing::array[i]);
return 0;
}
东西.hpp:
#pragma once
namespace thing {
extern int
a,
b,
array[10];
extern int func();
}
东西.cpp
#include "thing.hpp"
using namespace thing;
// I wanted to do the same thing with 'a' for all variables
int a,thing::b,thing::array[10];
int thing::func() {
return 12345;
}
错误:
/tmp/ccLbeQXP.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `thing::a'
collect2: error: ld returned 1 exit status
解决方案
using namespace thing
允许您使用thing
命名空间中的标识符,而无需在它们前面加上thing::
. 它有效地将它们拉入using
指令所在的命名空间(或全局命名空间)。
它不会将进一步的定义放入namespace thing
。因此,当您定义 时int a;
,它只是在全局命名空间中。您需要在命名空间中使用int thing::a;
或namespace thing { int a; }
定义它。
推荐阅读
- build - 在命令触发的 docker-compose build 之前执行一些 bash 脚本
- apache-camel - 如何解决 java.lang.NoClassDefFoundError: org/apache/camel/impl/DefaultComponent?
- css - 宽度属性会影响清除吗?
- python - 重塑数据框:列到行
- java - 说在 String 变量中可以存储所有 ASCII 符号是否正确?
- javascript - jQuery:如何克隆包含 p5 画布的 div?
- powershell - 获取连接属性名称
- npm - NPM 的 package-lock.json 中的层次结构代表什么?
- python - QFont.setFamily() 不适用于自定义字体
- database - Firestore:如何通过计算在用户和全局级别存储数据?