【发布时间】:2016-11-20 06:05:51
【问题描述】:
我知道在声明一个数组时我必须用一个常量值指定它的大小,但在这种情况下,我正在创建一个常量值,它也是一个常量表达式,用一个字面值初始化,可以在编译时间,但我在这两种情况下一直出错:
案例一:
堆栈.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
堆栈.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
堆栈.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 关键字修复了 CASE II,并且我在标题中使用 #define MAX 5 而不是使用一些常量变量来修复案例,这件事甚至很难我已经解决了我想要解决的问题对 C++ 有更好的了解,因为我不太了解,所以我想知道这些错误的原因。有人可以给我一个解释吗?提前致谢!
【问题讨论】:
标签: c++ arrays initialization stack constants