2011-03-14 38 views
1

有没有一种方法可以用一行代码来声明一个新的对象/继承变量?例如:如何在单个声明中设置继承的C++类/结构变量

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

回答

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; 
} 
+0

我喜欢这个答案在我的,他是正确的总是使用组成,你可以。 – Craig 2011-03-14 00:59:11

+0

太棒了!谢谢。我仍然在学习C++的功能。自学让我错过了一个教室会覆盖的很多东西。 – Zomgie 2011-03-14 01:07:07

+0

@Zomgie你应该阅读Herb Sutter的C++编码标准。它有助于所有这些类型的东西。 – Craig 2011-03-14 01:11:58

1

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

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

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