假设我们有以下文件(从C通过B.Stroustup ++编程语言所):C++双声明/定义?
stack.h
namespace Stack{
void push(int);
int pop();
class Overflow{};
}
stack.cpp
#include "stack.h"
namespace Stack{
const int max_size = 1000;
int v[max_size];
int top;
class Overflow{};
}
void Stack::push(int elem){
if(top >= max_size){
throw Overflow();
}
v[top++] = elem;
}
int Stack::pop(){
if(top <= 0){
throw Overflow();
}
return v[--top];
}
我不明白为什么stack.h中的类Overflow {}的声明/定义(?)也必须写入stack.cpp中?
写这样的代码是完全正确的吗?
UPDATE
的main.cpp
#include <iostream>
#include "stack.h"
using namespace std;
int main(){
try{
int a = 0;
while(true){
Stack::push(a++);
}
} catch(Stack::Overflow){
cout << "Stack::Overflow exception, YEAH!" << endl;
}
return 0;
}
予编译代码与: 克++ main.cpp中stack.cpp -o主
克++的i686-Apple苹果darwin11-llvm-g ++ - 4.2(GCC)4.2.1(基于Apple Inc. build 5658)(LLVM build 2336.11.00)
UPDATE
尝试过克++(Ubuntu的/ Linaro的4.7.3-1ubuntu1)(溶液)4.7.3代码给我一个错误:stack.cpp:7:9:错误:重新定义'class Stack :: Overflow'。这当然是正确的。
摘要:前面说过的在g ++上的mac版本有一个bug。
对我来说很奇怪。 –