簡體   English   中英

使用命名空間不適用於定義?

[英]using namespace does not work for definitions?

我無法理解c ++名稱空間。 請考慮以下示例:

//distr.h

namespace bogus{
    extern const int x;
    extern const int y;
    double made_up_distr(unsigned param);
}

現在如果我將變量定義為下面的cpp,那么編譯就好了

//distr.cpp

#include "distr.h"
#include <cmath>

const int bogus::x = 10;   
const int bogus::y = 100;

double bogus::made_up_distr(unsigned param){
    auto pdf = (exp(param) / bogus::x) + bogus::y;
    return pdf;
}

但是,如果我試圖簡單地引入bogus名稱空間並使用

//broken distr.cpp

#include "distr.h"
#include <cmath>

using namespace bogus;

const int x = 10;
const int y = 100;

double made_up_distr(unsigned param){
    auto pdf = (exp(param) / x) + y;
    return pdf;
}

我的編譯器告訴我,對xy的引用是不明確的。 這是為什么?

有一個簡單的原因,為什么這不能按預期的方式運作:

namespace bogus {
    const int x;
}
namespace heinous {
    const int x;
}

using namespace bogus;
using namespace heinous;

const int x = 10;

現在,上面的x應該引用bogus::xheinous::x還是新的global ::x 它將是沒有using語句的第三個,這意味着添加using語句將以一種特別微妙的方式改變現有代碼的含義。

using語句用於引入范圍的內容(通常但不一定是命名空間)以供查找 該聲明

const int x = 10;

除了檢測ODR違規外,通常不需要首先查找。

聲明/定義中的標識符的名稱查找與使用中的名稱查找的工作方式不同。 特別是,它不關心使用語句。 這有一個非常簡單的原因:如果它不同,它將導致各種令人討厭的驚喜。 考慮一下:

// sneakattack.h
namespace sneakattack { void foo(); }
using namespace sneakattack;

// somefile.cpp
#include "sneakattack.h"
void foo() { std::cout << "Hello\n"; }

// otherfile.cpp
void foo();
int main() { foo(); }

這個程序目前有效:聲明sneakattack::foo被忽略,定義::foo正確鏈接到otherfile中的用法。 但是如果名稱查找工作方式不同, sneakattack::foo會突然定義sneakattack::foo ,而不是::foo ,程序將無法鏈接。

暫無
暫無

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

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