2013-05-08 91 views
4

我想實現一個使用數組的堆棧,但我收到一個錯誤。獲取錯誤「數組綁定不是一個整數常量之前']'令牌'

class Stack{ 
private: 
    int cap; 
    int elements[this->cap]; // <--- Errors here 
    int top; 
public: 
    Stack(){ 
    this->cap=5; 
    this->top=-1; 
}; 

指示的線路有這些錯誤:

Multiple markers at this line 
- invalid use of 'this' at top level 
- array bound is not an integer constant before ']' token 

我在做什麼錯?

+0

對於一個'this'不存在有.... – Joe 2013-05-08 20:13:42

+1

...和C++沒有沃拉斯。 – 2013-05-08 20:14:18

+0

另外,編譯時必須知道成員數組的大小。 – 2013-05-08 20:14:20

回答

13

在C++中,數組的大小必須是編譯時已知的常量。如果情況並非如此,你會得到一個錯誤。

在這裏,你有

int elements[this->cap]; 

注意this->cap不是在編譯時已知常數,因爲它取決於cap有多大。

如果您希望稍後確定大小的可變大小的數組,請考慮使用std::vector,這可以在運行時調整大小。

希望這會有所幫助!

2

你不能在這樣的聲明中使用thisthis是傳遞給你的類中的非靜態方法的常量指針。它不在該範圍之外。

這樣的數組聲明需要常量值/表達式的大小。你不需要這個,你需要一個動態大小的容器。解決方案是使用std::vector

0

由於其他人已經解釋了這個問題的原因,這裏有一個可能的解決方案來解決它。由於看起來您可能不知道編譯時的數組大小,並且可能會考慮使用指針實現來限制使用std::vector<int>

#include <algorithm> 

class Stack{ 
private: 
    int cap; 
    int* elements; // use a pointer 
    int top; 
public: 
    Stack(){ 
     this->cap=5; 
     this->top=-1; 
     elements = new int[this->cap]; 
    } 

    Stack(const Stack& s) 
     : cap(s.cap) , top(s.top), elements(NULL) 
    { 
     if(cap > 0) { 
      elements = new int[cap]; 
     } 

     std::copy(s.elements , s.elements + cap, elements); 
    } 

    Stack& operator=(Stack s) { 
     swap(s, *this); 
     return *this; 
    } 

    ~Stack() {delete [] elements;} 

    friend void swap(Stack& first, Stack& second) 
    { 
     using std::swap; 
     swap(first.top, second.top); 
     swap(first.cap, second.cap); 
     swap(first.elements, second.elements); 
    } 
}; 
+0

我真的不知道如何實現複製構造函數和運算符==。你可以幫幫我嗎? – user1849859 2013-05-08 20:29:52

+0

@ user1849859已添加。閱讀[C++ copy-swap-idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)以充分理解爲什麼我們必須實現所有這些如果我們使用動態數組。 – andre 2013-05-08 20:48:00

0

變化

int elements[this->cap]; 

int* elements=new int[cap] 
+0

缺少分號。 – 2016-04-02 14:00:03

相關問題