gpt4 book ai didi

c++ - 虚拟继承使用

转载 作者:IT老高 更新时间:2023-10-28 22:15:18 28 4
gpt4 key购买 nike

我需要编写一个可供新手和有经验的 C++ 开发人员使用的编码约定。动态多态的继承规则是这样的:

  • For dynamic polymorphism, consider using single inheritance (tree-like hierarchy), possibly with multiple inheritance of abstract interfaces
  • for inheritance along the hierarchy (base classes, etc.), by default, use public inheritance
  • for inheritance of abstract interface, by default, use public virtual inheritance

此规则后面将提供有关实现、可能的异常(exception)情况等的详细信息。

那么,问题是:这个规则对新手和有经验的 C++ 开发人员都适用吗?(欢迎提供优点/缺点以及来源和链接)


我看到的是:

优点:

  • 新手易于使用的规则,不限制有经验的开发人员。
  • 熟悉那些已经熟悉 Java/.NET 接口(interface)的人
  • 避免了与实现的虚拟继承相关的问题(因为它是为抽象接口(interface)保留的),以及非虚拟继承(在转换为接口(interface)类时可能会产生歧义)

缺点:

  • 轻微的性能成本(转换到接口(interface)时的速度、虚拟表的大小、类实例中的附加指针)

注意:我已阅读以下在线资源:

注 2:“抽象接口(interface)”名称的使用是在 Sutter 和 Alexandrescu 在“C++ 编码标准”第 36 条中使用之后创造的


这是一种应该可以工作的情况(使用接口(interface)的 Java/C# 等价物也可以工作),但如果接口(interface)继承不是虚拟的,则在 C++ 中就不行:

class A
{
public :
virtual ~A() = 0 {}
} ;

class B : public A {} ; // should have been virtual to avoid the error
class C : public A {} ; // should have been virtual to avoid the error

class D : public B, public C
{
public :
virtual ~D() {}
} ;

void foo(A * c) {}
void bar(D * d)
{
foo(d) ; // Error: ambiguous conversions from 'D *' to 'A *
}

是的,为了消除歧义而进行显式转换是错误的解决方案(无论如何,显式转换通常是错误的解决方案)。

最佳答案

你知道吗?您已经在问题中提供了所有重要信息。在技​​术层面上,我看不出有什么可以回答的。而且显然没有其他人发现您发布的内容有任何重大技术问题。

不过,我会回答你的粗体问题:是的,它适合新手和专业人士。

  • 新手有一些有用的技术指南。
  • 专业人士可以做他们想做的事如果他们可以给出理由,因为你用“考虑”和“默认”来限定你的规则,所以基本上没有其他人可以说你必须这样做或所以因为样式规则,因为你的规则的措辞已经允许异常(exception)。

关于c++ - 虚拟继承使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20327894/

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