2016-11-20 88 views
0

我知道當聲明一個數組時,我必須用一個常量值指定它的大小,但在這種情況下,我創建了一個const值,它也是一個常量表達式與一個文字值,其可以在編譯時計算初始化,但一直具有關於這兩個情況下,錯誤:C++:Error在多個文件中初始化Const變量的數組大小

CASE I:

Stack.h

#ifndef STACK_H 
#define STACK_H 

extern const unsigned MAX; 

class Stack { 

public: 
    /* Declarations here ... */ 

private: 
    unsigned n; 
    int stack[MAX]; 

}; 

#endif // STACK_H 

Stack.cpp

#include <iostream> 
#include "Stack.h" 

extern const unsigned MAX = 5; 

Stack::Stack() { 
    this->n = 0; 
} 

int Stack::pop() { 
    int pop = -1; 

    if (n > 0) { 
     pop = this->stack[n - 1]; 
     this->stack[n - 1] = 0; 
     --n; 
    } else { 
     std::cout << "StackUnderFlowException:: Stack Data Structure is Empty!" << std::endl;; 
    } 

    return pop; 
} 

int Stack::getStackTop() { 
    return this->n > 0 ? this->stack[n - 1] : -1; 
} 

void Stack::push(int v) { 
    if (n < MAX) { 
     this->stack[n] = v; 
     ++n; 
    } else { 
     std::cout << "StackOverFlowException:: Stack Data Structure is Full!" << std::endl; 
    } 
} 

錯誤:

In file included from p38.cpp:2: 
./Stack.h:18:6: error: fields must have a constant size: 'variable length array in structure' extension will never be supported 
     int stack[MAX]; 
      ^
1 error generated. 
In file included from Stack.cpp:2: 
./Stack.h:18:6: error: fields must have a constant size: 'variable length array in structure' extension will never be supported 
     int stack[MAX]; 
      ^

而且事情變得即使在第二種情況下更加怪異......

案例二:

Stack.h 

#ifndef STACK_H 
#define STACK_H 

extern const unsigned MAX = 5; 

class Stack { 

public: 
    Stack(); 
    int pop(); 
    int getStackTop(); 
    void push(int v); 
    bool isEmpty(); 
    void printStack(void) const; 

private: 
    unsigned n; 
    int stack[MAX]; 

}; 

#endif // STACK_H 

Stack.cpp

#include <iostream> 
#include "Stack.h" 

using namespace std; 

Stack::Stack() { 
    this->n = 0; 
} 

/*更多鱈魚Ë在這裏... */

錯誤:

duplicate symbol _MAX in: 
    /var/folders/r3/zbrrqh7n5tg0vcnpr9_7j0nr0000gn/T/p38-ac46b9.o 
    /var/folders/r3/zbrrqh7n5tg0vcnpr9_7j0nr0000gn/T/Stack-a5d98e.o 
ld: 1 duplicate symbol for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

我剛剛通過刪除extern關鍵字固定的情形II,和情況下,我在報頭使用中的#define MAX 5,而不是使用一些固定的常量變量,事情甚至很難我已經解決了這個問題我想更好地理解C++,我想知道這些錯誤的原因,因爲我沒有很好地理解它。有人能給我一個解釋嗎?提前致謝!

回答

1

編譯時間常數和運行時間常數之間有區別。

extern const unsigned MAX; 

聲明運行時間常數,而不是編譯時間常量。它可以在運行時初始化爲5,10,20或其他任何東西。一旦初始化,其價值保持不變。

由於它不是一個編譯時間常量,它不能用作數組的大小。

要使用它作爲編譯時間常數,使用:

const unsigned MAX = 5; 

在.h文件。


extern const unsigned MAX = 5; 

不起作用,因爲不僅聲明變量,但定義它。任何.c文件#include是.h文件最終定義的變量,它說明了重複符號鏈接器錯誤。

+0

謝謝,讓我更好地理解CASE I中的錯誤,我不知道extern關鍵字聲明運行時,當編譯時需要知道數組中的const值。萬分感謝!!你對CASE II的錯誤有什麼想法嗎? –

+0

@ Pj-,請參閱最新的答案。 –

0

int stack [MAX];

你的錯誤在這裏,你必須強制指定大小。 e。g int stack [20];