如何在单个声明中设置继承的C++类/结构变量

Zom*_*gie 1 c++ variables inheritance struct class

是否有一种方法可以用一行代码声明一个具有继承变量的新对象?例:

#include <iostream>

using namespace std;

struct item_t {
    string name;
    string desc;
    double weight;
};

struct hat_t : item_t
{
    string material;
    double size;
};

int main () 
{
    hat_t fedora; // declaring individually works fine
    fedora.name = "Fedora";
    fedora.size = 7.5;

    // this is also OK
    item_t hammer = {"Hammer", "Used to hit things", 6.25}; 

    // this is NOT OK - is there a way to make this work?
    hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, "straw", 6.5}; 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 5

具有继承的类不是POD,因此绝对不是聚合.如果您不使用虚函数,请选择组合继承.

struct item_t {
    string name;
    string desc;
    double weight;
};

struct hat_t
{
    item_t item;
    string material;
    double size;
};

int main () 
{
    // this is also OK
    item_t hammer = {"Hammer", "Used to hit things", 6.25}; 

    // this is now valid
    hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, "straw", 6.5}; 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)