2011-10-05 22 views
3

我正在嘗試創建一個HashTable類的輪廓。我從Visual Studio中獲得了3個錯誤輸出,但我在這裏看不到問題。我在C++中對OO相當陌生,所以這可能是我錯過的東西。它聲稱我的向量數組有問題。的錯誤是:語法錯誤:OO中的向量數組C++

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

這是我的完整的類,它現在是相當空:

#include <iostream> 
#include <vector> 
#include "stdafx.h" 
using namespace std; 

class HashTable 
{ 
private: 
    const static int buckets = 100; 
    vector<int> hashTable[buckets]; //Internal storage 

    int hash(int toHash); //Performs hash function 

public: 
    HashTable(); //Constructor 
    HashTable(int s); //Constructor 
    ~HashTable(); //Destructor 

    void add(int toAdd); //Adds an element to the HashTable 
    void remove(int toDelete); //Deletes an element from the HashTable 
    bool search(int toSearch); //Returns true if element in HashTable, false otherwise 
    int getSize(); //Returns size of HashTable 
    void print(); //Prints current state of the hashtable 

    //TODO more methods...? 




}; 

//Definitions... 

HashTable::HashTable() 
{ 
} 

HashTable::~HashTable() 
{ 
    //cout << "Destroyed" << endl; 
} 

void HashTable::add(int toAdd) 
{ 

    //elements[hash(toAdd)] = toAdd; 

} 

void HashTable::remove(int toDelete) 
{ 

} 


bool HashTable::search(int toSearch) 
{ 

} 

int HashTable::getSize() 
{ 
    //return size; 
} 


void HashTable::print() 
{ 

} 


int main() 
{ 

    return 0; 
} 
+0

爲什麼不使用'vector > hashTable;' –

+0

只是在類體內聲明桶並在類聲明外定義它 –

+0

如果刪除'#include「stdafx.h」'會發生什麼?在VC++ 2010中,我得到的唯一錯誤與函數沒有返回聲明的值有關。 –

回答

4

的C++這裏是有效的(一旦你在空函數填寫)。問題在於Visual C++如何使用預編譯頭文件。當您使用預編譯頭文件(默認設置)時,Visual C++編譯器希望每個實現文件的第一行爲#include "stdafx.h",並且不編譯之前出現的任何內容。

這意味着您的代碼中包含的<vector>被忽略,因此編譯vector<int>會導致錯誤。

如果你將#include "stdafx.h"這條線移動到頂部,應該編譯。或者你可以在項目設置中禁用預編譯頭文件。

+0

這就是討厭的人。在這個頁面加入書籤 – Sodved

+0

啊,很好看,這是解決問題的方法。忘記它必須在頂部。這也一定是我之前不能在方法定義中使用'cout'的原因。謝謝! –