2010-07-28 194 views
0

這很奇怪。我在一個類中創建了一個向量,但無法在另一個類中創建它。他是什麼,我有一個表示:C++無法創建矢量

main.h

#include <Windows.h> 
#include <ShellAPI.h> 
#include <vector> 
#include <string> 
#include <iostream> 

#include "taco.h" 

class MyClass 
{ 

public: 
    int someint; 
    vector<int> myOrder; 
}; 

taco.h

#include <vector> 

class OtherClass 
{ 

public: 
    vector<int> otherOrder; 
}; 

我也得到編譯關於向量聲明錯誤taco.h:

error C2143: syntax error : missing ';' before '<' 
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
error C2238: unexpected token(s) preceding ';' 

我在這裏錯過了什麼?我可以取消註釋掉第二個向量聲明並且編譯好。

+4

這表明,我認爲一些.h文件中已'使用命名空間std;'在它的地方,這通常是一個壞主意。 'using'不應該在頭文件中完成,因爲它會爲任何直接或間接包含該頭文件的.cpp文件調整名稱空間。僅對源文件使用''使用',效果是本地的。 – 2010-07-28 18:09:06

回答

11

嘗試:

std::vector<int> otherOrder; 

vectorstd命名空間的一部分。這意味着只要在頭文件中使用vector,就應該包含前綴std::

你有時可能忘記忘記它的原因是一些包含的文件可能包含using namespace std;,允許你忽略前綴。但是,您應該避免在頭文件中使用using關鍵字,因爲它會污染include它的任何文件的名稱空間。

有關using namespace ...的危險性的更詳細說明,請參閱this thread

+1

[This answer](http://stackoverflow.com/questions/2879555/c-stl-how-to-write-wrappers-for-cout-cerr-cin-and-endl/2880136#2880136)是另一種反對意見'使用名稱空間std'。 – sbi 2010-07-28 18:10:37

+0

@sbi:謝謝,很好的論點。 – 2010-07-28 18:14:25

+0

嗯由於某種原因,我認爲我在main.h中使用namespace std會級聯到taco.h.感謝你的回答! – 2010-07-28 18:17:02

3

嘗試std::vector<int>。你應該使用命名空間---我假設你有

using namespace std; 

main.h某處。關於爲什麼使用using是不好的做法,有很多關於這個問題的討論;我建議你檢查一下。

3

所有C++標準庫對象都位於std命名空間中。嘗試

class MyClass 
{ 

public: 
    int someint; 
    std::vector<int> myOrder; 
// ^^^^^ 
};