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

#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;
}

最佳答案

具有继承的类不是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;
}

07-24 09:46
查看更多