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

时间:2011-03-14 00:47:21

标签: c++ class inheritance variables struct

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

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

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

我相信拥有基类会阻止C ++ 03中的聚合初始化语法。 C ++ 0x使用大括号进行更一般的初始化,因此更有可能在那里工作。

答案 2 :(得分:1)

你可以使用构造函数吗?

struct item_t {
item_t(string nameInput, string descInput, double weightInput):
name(nameInput),
desc(descInput),
weight(weightInput)
{}

string name;
string desc;
double weight;
};

struct hat_t : item_t
{
    hat_t(string materinInput,d double sizeInput string nameInput, string descInput, double weightInput) :
    material(materialInput), size(size), item_t(nameInput, descInput, weightInput)
{}

string material;
double size;
};

然后你可以调用你想要的构造函数。

相关问题