2012-09-14 33 views
1

我有以下代碼在全局函數中打印派生結構變量。但是當我試圖編譯代碼時,g ++返回以下錯誤。是否不可能從通過值傳遞給函數的基類將結構轉換爲派生類?類型轉換的遺傳結構給g ++ compliation錯誤

In function 'void print(B)': 
Line 19: error: no matching function for call to 'D1::D1(B&)' 

代碼:

struct B{ 
    int a; 
    B() 
    { 
     a = 0; 
    } 
}; 

struct D1:public B{ 
    std::string s1; 
    D1() 
    { 
     s1.assign("test"); 
    } 
}; 

void print(B ib) 
{ 
    cout << static_cast<D1>(ib).s1<<endl; 
} 

int main() 
{ 
    D1 d1; 
    cout << d1.s1 <<endl; 
    print(d1); 
    return 0; 
} 
+0

嗯,哦,什麼是垃圾代碼......聽說過構造函數初始值列表*? – Griwes

+0

@Griwes:我知道構造函數初始值設定項列表。我複製了我在機器上試過的代碼。對於那個很抱歉。 – Ravi

回答

4
void print(B ib) 

D1 d1; 
print(d1); 

你的對象是在print功能截斷爲B。您應該使用referencepointer而不是值。

cout << static_cast<D1>(ib).s1<<endl; 

使用static_cast<D1&>(ib).s1。在這兩種情況下都應該參考ib

+1

確實。 http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c – BoBTFish

+1

'dynamic_cast'只適用於多態類型。如果函數需要,將參數類型更改爲「D1」(可能帶有「const」和/或「&」)會更好。 –

+0

@BoBTFish:Link向我解釋了切片問題。非常感謝 – Ravi