簡體   English   中英

如何使用“使用命名空間”在命名空間中定義變量?

[英]How do I define a variable in a namespace with “using namespace”?

所以我有一個命名空間thing ,它在 header 中聲明了extern int變量。 我正在嘗試using namespace thing; 簡化初始化,但在嘗試在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指令所在的命名空間(或全局命名空間)。

它沒有將進一步的定義放入命名空間thing中。 所以當你定義int a; ,它只是在全局命名空間中。 你需要使用int thing::a; namespace thing { int a; } namespace thing { int a; }在命名空間中定義它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM