C++从外部类继承的嵌套类;不允许使用不完整的类型

C++ nested class which inherits from the outer class; Incomplete type not allowed

本文关键字:用不完 类型 不允许 嵌套 从外部 继承 C++      更新时间:2023-10-16

在 kotlin 中,有一种设计模式,您可以使用密封类模拟具有关联值的 swift 枚举,并使用嵌套类从中继承

https://medium.com/@da_pacheco/using-kotlins-sealed-class-to-approximate-swift-s-enum-with-associated-data-7e0abac88bbf

例如;斯威夫特有:

enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}

Kotlin 模仿:

sealed class Barcode {
class UPCA(val system: Int, val manufacturer: Int, val product: Int, val check: Int) : Barcode()
class QRCode(val productCode: String) : Barcode()
}

然后,您可以执行一些操作,例如列出Barcode并遍历所有内容。

您也可以在 Java 和 C# 中使用此模式...没有"密封类",所以你不能阻止未来的人们扩展列表,但它足够接近并且非常方便。

所以现在我正在尝试在C++中执行此操作,并且收到错误消息"不允许不完整的类型">

class ActionToPerform
{
public:
class ClearItems: public ActionToPerform
{ };
};

这是有一定道理的,因为ActionToPerform类型在编译器ClearItems时没有完全声明,但它也是愚蠢和烦人的。我可以将ClearItems类移出ActionToPerform但随后我失去了范围/命名空间的好处。

有没有办法解决这个问题? 或者这只是C++固有的限制?

只需转发声明您的派生类:

class ActionToPerform
{
public:
class ClearItems;
};
class ActionToPerform::ClearItems: public ActionToPerform
{ };