爲什麼要儘量避免使用using namespace std

  在C++中,爲了避免命名衝突,我們可以通過namespace對各個類庫、方法進行分割命名空間。

  如下所示:

#include <iostream>
#include <string>

namespace fruit {
    void printColor(const std::string& name)
    {
        std::cout << "fruit name: " << name << std::endl;
    }
}

namespace vegetable {
    void printColor(const char* name)
    {
        std::cout << "vegetable name: " << name << std::endl;
    }
}

using namespace fruit;
using namespace vegetable;

int main()
{
    printColor("apple");
    printColor(std::string("apple2"));

}

運行結果:

 

 

  由於此處的兩個函數的參數不一致,發生了重載。同樣,如果在我們的頭文件中使用了using namespace std,

就無意中導致擴大了std命名空間的影響到的域,導致std中的類、方法與其它域中同名的類、方法產生衝突混亂,

實際使用的類、方法可能並不是我們希望使用的。給調試工作帶來了不必要的麻煩。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章