gpt4 book ai didi

c++ - Using Declaration 和 Forward Declaration 之间的冲突

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:49 24 4
gpt4 key购买 nike

让我们和 Bulldog 一起去散步 :)

假设我有一个命名空间 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 的声明注入(inject) 到命名空间 Street 作为 Street::Bulldogusing 声明。

然后,我有 Owner.hpp,其中类 Bulldog forward declared:

namespace Street {
class Bulldog;

class Owner {
Bulldog* bulldog;
};
}

最后,我有了 Owner.cpp:

#include "Owner.hpp"
#include "Bulldog.hpp"

namespace Street {
// Implementation of Owner...
}

编译错误发生在Owner.cpp:

错误:“Bulldog”已在此范围内声明

这种现象的自然解释似乎是 C++ 将这 2 个 Bulldog 类视为不同的,但为什么呢?在这种情况下,我看不出有任何歧义,即如果编译器正确实现,它实际上可以工作。

您可以建议哪些解决方法?我能想到的一种方法是简单地从 Owner.hpp 中删除 Bulldogforward declaration 并移动 #include "Bulldog.hpp"Owner.cppOwner.hpp。但是,这将导致完全包含而不是前向声明

最佳答案

看来你可以通过将 Bulldog.hpp 更改为 say 来解决此问题

namespace Street {
namespace House {
class Bulldog;
}
using House::Bulldog;

// ...
}

这在 Clang 中对我有用。

关于c++ - Using Declaration 和 Forward Declaration 之间的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15375051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com