我知道當聲明一個數組時,我必須用一個常量值指定它的大小,但在這種情況下,我創建了一個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++,我想知道這些錯誤的原因,因爲我沒有很好地理解它。有人能給我一個解釋嗎?提前致謝!
謝謝,讓我更好地理解CASE I中的錯誤,我不知道extern關鍵字聲明運行時,當編譯時需要知道數組中的const值。萬分感謝!!你對CASE II的錯誤有什麼想法嗎? –
@ Pj-,請參閱最新的答案。 –