2015-12-13 24 views
0

我有一個C++源代碼文件。那就是:問題與「使用命名空間標準;」

#include <iostream> 
using namespace std; 

class myPoint 
{ 
public: 
    double x; 
    double y; 
    myPoint() {x=y=0;} 
}; 

double distance(myPoint A, myPoint B) 
{ 
    return (A.x - B.x); 
} 

int main() 
{ 
    myPoint A, B; 
    A.x=5; A.y=5; 
    B.x=3; B.y=2; 
    cout << distance(A, B) << endl; 
    return 0; 
} 

我的編譯器(微軟的Visual Studio C++ 2012)給了我以下錯誤:

...
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(364): error C2039: 'iterator_category' : is not a member of 'myPoint'
1> d:...\source.cpp(5) : see declaration of 'myPoint'
...

當我刪除using namespace std; ,改變cout << distance(A, B) << endl;std::cout << distance(A, B) << std::endl; 我的程序工作。

爲什麼第一個版本給我一個錯誤?什麼是錯誤?

+0

請參閱http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – juanchopanza

+0

有一個原因,標準庫將其名稱放在命名空間'std'中。吹走命名空間不是一個好主意。 –

回答

2

你有衝突std::distance

3

Why I cannot use 1st version of the source code? Where

因爲你不經意的一個名稱被拉離std命名空間(std::distance)是一樣的,你定義的別的東西的名稱(distance)。這給你一個衝突。

Where is the mistake?

的根本錯誤是說using namespace std;,特別是如果你沒有在標準庫知道每一個名字,過去未來。

在自己的名字空間中定義自己的名字也很有意義。

namespace mystuff { 
    class Point { ... }; 
    double distance(const Point& A, const Point& B); 
} 
2

有一個在標準庫中的std::distance,它因爲using namespace std;變得可見,似乎出於某種原因它,而不是拿起你的版本。請使用using namespace std;。如果你堅持,不要使用聽起來像普通英語單詞的名字,因爲它們很可能與圖書館名稱發生衝突。