我有以下代碼在全局函數中打印派生結構變量。但是當我試圖編譯代碼時,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;
}
嗯,哦,什麼是垃圾代碼......聽說過構造函數初始值列表*? – Griwes
@Griwes:我知道構造函數初始值設定項列表。我複製了我在機器上試過的代碼。對於那個很抱歉。 – Ravi