2014-03-25 48 views
17

我有一个所谓的“例外”命名空间的问题命名空间称为“异常”会导致编译问题

让我们看看下面的例子标题:

#include <exception> 

namespace exception 
{ 
    struct MyException : public std::exception 
    {}; 
} 


struct AnotherException : public exception::MyException 
{ 
    AnotherException() : exception::MyException() { } 
}; 

这头不与下面的错误编译:

 

    namespacetest.hpp: In constructor 'AnotherException::AnotherException()': 
    namespacetest.hpp:12:48: error: expected class-name before '(' token 
    namespacetest.hpp:12:48: error: expected '{' before '(' token 

这有两种解决方案:

1)在第12行用“::”限定命名空间

AnotherException() : ::exception::MyException() { } 

2)将命名空间重命名为例如“例外”

是什么原因,命名空间“异常”导致混淆?我知道有一个类std :: exception。这是否会造成麻烦?

回答

22

I know that there is a class std::exception . Does this cause the trouble?

是的。在std::exception内,不合格名称exception注入类名称。这是继承的,所以在你的班级中,一个不合格的exception指的是,而不是你的名字空间。

+2

感谢您在发布答案的那一刻获得+1的结果? :) – jrok

+0

+1表示“注入” –

10

+1 @Mike Seymour的回答!作为补充,还有比当前解决方案更好的方法来防止歧义:

只需使用MyException,没有任何名称空间限定:

struct AnotherException : public exception::MyException 
{ 
    AnotherException() : MyException() { } 
}; 

LIVE EXAMPLE

或者使用C++ 11的遗传构造特点:

struct AnotherException : public exception::MyException 
{ 
    using MyException::MyException; 
}; 

LIVE EXAMPLE