gpt4 book ai didi

c++ - 冲突声明(外部基础与派生)

转载 作者:行者123 更新时间:2023-11-28 04:09:17 27 4
gpt4 key购买 nike

简单的例子:

class PublicInterface {}; // e.g. GSM driver with 'send_sms' 
extern PublicInterface theThing; // for most of the code (in common header)

class PrivateImplementation : public PublicInterface {}; // implementation not all need to know about
PrivateImplementation theThing; // the one and only GSM driver with all it needs to work

无法编译,提示 PrivateImplementation theThingextern PublicInterface theThing 冲突。好的,我还有其他选择,比如拥有全局指针 (extern PublicInterface *publicThing) 大多数其他代码都可以使用(我在初始化期间将其设置为 publicThing = &theThing ).我也可以将它全部包装在一个命名空间而不是一个类中(设备永远不会有两个 GSM 模块),或者我可以玩一些技巧来禁用源的 extern PublicInterface theThing实现(以及任何其他可能希望访问更具体的东西 - 使用 extern PrivateImplementation theThing 代替)它甚至可以工作。

问题是:那为什么会出现错误?当我在某些来源中有 extern PublicInterface theThing 时,它就可以工作,extern PrivateImplementation theThing 在其他来源和 PrivateImplementation theThing; 只有一个(IAR EWARM - 目标 ATSAM4L)。

我能想到的可能的问题:

  1. 虚方法(在派生类中但不在基类中)或多重继承(基类在派生类中排在第二位)。小技术问题,但可以解决:链接器需要知道在哪种类型下引用它以注入(inject)正确的地址 - 对于公共(public)访问可能有所不同(更高一点),它实际上存在于派生内部(在 vmt 或第一个基类之后) .编译器可以使用指针(在 publicThing = &theThing 中轻松地将指针转换为派生指针到基指针),因此它可以(理论上)为全局变量做到这一点 - 可解决.

  2. 方法隐藏(可能包括对析构函数的显式调用)。没问题,因为我们在声明中说了我们想要看到和使​​用的内容(最后的声明获胜)。

  3. 允许更改的规则 - 不能声明它一次 intdouble 第二次,或者它至少应该警告。

    <

有什么实际问题吗? (我的意思是无法解决的问题。)

什么地方可能出错? (例如,当我耍花招在某些来源中使用 extern Public... 并在其他来源中使用 extern Private... 时,但绝不会同时使用,永远不会触发冲突,得到正常运行的东西。)

编辑 - 对一些评论的回应:

所以,您基本上是在向我指出 One Definition Rule .这至少部分回答了我的担忧(是的,坚持使用指针 - publicThing,不要耍花样)。没有真正回答 为什么 部分,但链接中的示例本身显示了它可能在编译器中触发的问题(没有看到 CDummy 在两个不同的来源中是两个不同的东西).另外幸运我没有触发我自己提到的第一个问题(多重继承)。仍然没有回答为什么,但这对于 Stack Overflow 来说可能太概念化了,对吧?

最佳答案

“为什么”这个问题有点难以理解。 theThing 是代码中对象的名称(不是指针或对它的引用)。 C++ 是静态类型语言,因此一个对象实际上只能是一种类型。时期。您可以在 C++ 中拥有多态指针或引用。所以你需要做类似的事情:

class PublicInterface {}; // e.g. GSM driver with 'send_sms' 
extern PublicInterface& theThing; // declaration of reference

class PrivateImplementation : public PublicInterface {}; // implementation not all need to know about
PrivateImplementation thing; // the one and only GSM driver with all it needs to work
PublicInterface& theThing = thing; // definition of the reference to thing

关于c++ - 冲突声明(外部基础与派生),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168507/

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