gpt4 book ai didi

c++ - 继承结构的类型转换给出 g++ 编译错误

转载 作者:行者123 更新时间:2023-11-30 02:03:07 24 4
gpt4 key购买 nike

我有以下代码在全局函数中打印派生结构变量。但是当我尝试编译代码时,g++ 返回以下错误。是否无法将结构从基类类型转换为派生类,而基类通过值传递传递给函数?

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

最佳答案

void print(B ib)

D1 d1;
print(d1);

您的对象被截断为 Bprint功能。你应该使用 referencepointer而不是值(value)。

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

使用 static_cast<D1&>(ib).s1 .在这两种情况下 ib应该是引用!

关于c++ - 继承结构的类型转换给出 g++ 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com