2012-05-24 94 views
3

這是一類,我在2010年的Visual C++速成工作頭:矢量<int> - 缺少類型說明

/* custom class header to communicate with LynxMotion robot arm */ 

#include <vector> 
using namespace System; 
using namespace System::IO::Ports; 

public ref class LynxRobotArm 
{ 
public: 
    LynxRobotArm(); 
    ~LynxRobotArm(); 
    void connectToSerialPort(String^ portName, int baudRate); 
    void disconnectFromSerialPort(); 
    void setCurrentPosition(int channel, int position); 
    int getCurrentPosition(int channel); 
    void moveToPosition(int channel, int position); 

private: 
    void initConnection(); 
    SerialPort^ serialPort; 
    array<String^> ^serialPortNames; 
    String^ portName; 
    int baudRate; 
    vector<int> currentPosition; 
}; 

一切工作正常,直到我改變了最後一行int currentPositionvector<int> currentPosition。如果我現在嘗試編譯/調試,我得到這些錯誤消息:

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 ';' 

我查MSDN對這些錯誤代碼的一些更多的信息,但我無法弄清楚什麼是錯的代碼。有任何想法嗎?

回答

7

vector是在std命名空間內定義的模板,因此您應該編寫std::vector<int>而不是vector<int>

另外,您可以在這個文件的開頭寫using namespace std;,但請注意,這被認爲是不好的做法,因爲它可能會導致您的某些類的名字,成爲曖昧。

+0

這可能是不好的做法,但我知道在我的大學裏他們鼓勵使用'using namespace std;'。我有時會因爲編程教學而感到震驚。 – Drise

+1

@Drise:在許多其他文件包含的頭文件中(以及使用名稱空間標準擴展名)使用它是不好的做法。 – LihO

+0

我想說你只能用'namespace std;'來搞砸你的實現文件(我認爲它沒有太多,如果有的話),但是如果你開始把它們放到頭文件中,很快就會變得非常糟糕。 –

0

正在使用載體。 Vector包含在命名空間std中。命名空間封裝了一個變量/類的正常範圍。無法以某種方式解決範圍問題,您無法訪問命名空間內的元素。主要有3種途徑去了解這一點:

#include <vector> 
using namespace std; 

你不一般要使用這一個,它會產生問題,因爲它可以讓你看到包含在命名空間std任何函數/類。這勢必會導致命名衝突。

下一個方法是:

#include <vector> 
using std::vector; 

這種方式是更好一點。它使矢量對文件或包含所述文件的任何文件中的任何內容都可見。它可能在.cpp文件中完全無害,因爲不應該包含.cpp文件。你應該知道你是不是符號。在.h/.hpp文件的場景中,您可能仍然不想使用它。任何具有.hpp文件的文件都包含它們的源代碼,將會將類向量視爲名稱定義。這可能對您的代碼的用戶不利,因爲他們可能並不期望該符號被定義。在HPP文件的情況下,你應該總是使用下列內容:

#include <vector> 

class myClass{ 
private: 
     std::vector myVector; 
}; 

使用命名空間這樣保證了它纔可以看到究竟在何處使用符號,和其他地方。這是我在.hpp文件中使用它的唯一方法。

+0

這不提供問題的答案。一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你將能夠[評論任何職位](http://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/12573191) – Suever

+1

好吧,我會修復我的答案,使其更有意義。 – HumbleWebDev

相關問題