首页 > 解决方案 > 如何使用“使用命名空间”在命名空间中定义变量?

问题描述

所以我有一个名称空间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

标签: c++

解决方案


using namespace thing允许您使用thing命名空间中的标识符,而无需在它们前面加上thing::. 它有效地将它们拉入using指令所在的命名空间(或全局命名空间)。

它不会将进一步的定义放入namespace thing。因此,当您定义 时int a;,它只是在全局命名空间中。您需要在命名空间中使用int thing::a;namespace thing { int a; }定义它。


推荐阅读