【发布时间】:2013-09-21 18:14:08
【问题描述】:
假设我们有以下文件(取自 B.Stroustup 的 The C++ Programming language):
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中?
编写这样的代码是否正确?
更新
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;
}
我使用以下代码编译代码: g++ main.cpp stack.cpp -o main
g++ i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1(基于 Apple Inc. build 5658)(LLVM build 2336.11.00)
更新(解决方案)
尝试过 g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3 代码给了我一个错误:stack.cpp:7:9: error: redefinition of 'class Stack::溢出'。这当然是正确的。
总结:之前说的mac上g++版本有bug。
【问题讨论】:
标签: c++ exception declaration