2011-03-14 28 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; 
}; 

然後你可以調用你想要的構造函數。