简体   繁体   English

在聚合初始化期间无法访问继承的结构成员

[英]Inherited struct members inaccessible during aggregate initialization

struct BasePluginInfo
{
    bool bHasGui, bIsSynth;
    char cType;
    std::string sCategory, sSdkVersion, sVendor, sVersion;
};

struct PluginClassInfo
{
    std::string sName, sUid;
    std::vector<std::string> vsParamNames;
};

struct ShellPluginInfo : BasePluginInfo
{
    std::vector<PluginClassInfo> vciClasses;
};

When I do当我做

ShellPluginInfo
{
    .bHasGui = true
};

The compiler complains that ShellPluginInfo has no field 'bHasGui' .编译器抱怨ShellPluginInfo has no field 'bHasGui'

However this works:但是,这有效:

ShellPluginInfo info;
info.bHasGui = true;

SO complains I have too much code, so these are a few words to fill it up.所以抱怨我有太多的代码,所以这些是几句话来填补它。

When aggregate initializing something with base classes, the base class acts like a member of the class, similar to if you had:当使用基类聚合初始化某些东西时,基 class 就像 class 的成员一样,类似于您有:

struct ShellPluginInfo {
    BasePluginInfo __base_class_subobject;
    std::vector<PluginClassInfo> vciClasses;
};

As such, the first clause in the initializer list will try to initialize it, and you have to write:因此,初始化列表中的第一个子句将尝试初始化它,您必须编写:

ShellPluginInfo{  // This initializer list initializes a ShellPluginInfo
    { .bHasGui = true; }  // This initializer list initializes a BasePluginInfo
}

However, since this is not a designated initializer, you cannot use designated initializers for the rest of the members of the derived class.但是,由于这不是指定的初始值设定项,您不能为派生 class 的成员的 rest 使用指定的初始值设定项。 For example:例如:

ShellPluginInfo{
    {  // (note: doesn't have a designator)
        .bHasGui = true,
        .cType = 'a'  // OK
    },
    .vciClasses = {}  // ERROR: Can't mix designated and non-designated initializers

}

This proposal attempts to remedy that: https://wg21.link/p2287r1 , making your original attempt valid.该提案试图纠正这一点: https://wg21.link/p2287r1 ,使您的原始尝试有效。 It has not been accepted yet though, but you may see it in C++23.虽然它还没有被接受,但你可能会在 C++23 中看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM