【发布时间】:2013-02-28 18:46:08
【问题描述】:
我们和斗牛犬一起去散步吧:)
假设我有一个命名空间 Street::House(在命名空间 Street 内),其中类 Bulldog 被声明(让它在 House/Bulldog.hpp 中):
namespace Street {
namespace House {
class Bulldog {};
}
}
然后,我有Bulldog.hpp:
#include "House/Bulldog.hpp"
namespace Street {
using House::Bulldog;
}
注意发生了什么:我将Street::House::Bulldog 的声明注入 到命名空间Street 作为Street::Bulldog 和using 声明。
然后,我有 Owner.hpp 类 Bulldog 被转发声明:
namespace Street {
class Bulldog;
class Owner {
Bulldog* bulldog;
};
}
最后,我有Owner.cpp:
#include "Owner.hpp"
#include "Bulldog.hpp"
namespace Street {
// Implementation of Owner...
}
Owner.cpp出现编译错误:
error: 'Bulldog' is already declared in this scope
这种现象的自然解释似乎是 C++ 将这 2 个Bulldog 类视为不同,但为什么呢?在这种情况下,我看不出有任何歧义,也就是说,如果编译器正确实现它,它实际上可以工作。
您可以建议哪些解决方法?我能想到的一种方法是简单地从Owner.hpp 中删除Bulldog 的前向声明,并将#include "Bulldog.hpp" 从Owner.cpp 移动到Owner.hpp。但是,这将导致完全包含而不是前向声明。
【问题讨论】:
-
Clang 有一个更具描述性的消息
error: target of using declaration conflicts with declaration already in scope -
这不是编译器错误,注入的声明不能这样工作。
标签: c++ compiler-errors include forward-declaration using-declaration