C++:Error在多个文件中初始化Const变量的数组大小
问题描述:
我知道当声明一个数组时,我必须用一个常量值指定它的大小,但在这种情况下,我创建了一个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++,我想知道这些错误的原因,因为我没有很好地理解它。有人能给我一个解释吗?提前致谢!
答
编译时间常数和运行时间常数之间有区别。
extern const unsigned MAX;
声明运行时间常数,而不是编译时间常量。它可以在运行时初始化为5,10,20或其他任何东西。一旦初始化,其价值保持不变。
由于它不是一个编译时间常量,它不能用作数组的大小。
要使用它作为编译时间常数,使用:
const unsigned MAX = 5;
在.h文件。
extern const unsigned MAX = 5;
不起作用,因为不仅声明变量,但定义它。任何.c文件#include
是.h文件最终定义的变量,它说明了重复符号链接器错误。
答
int stack [MAX];
你的错误在这里,你必须强制指定大小。 e。g int stack [20];
谢谢,让我更好地理解CASE I中的错误,我不知道extern关键字声明运行时,当编译时需要知道数组中的const值。万分感谢!!你对CASE II的错误有什么想法吗? –
@ Pj-,请参阅最新的答案。 –