[英]Can struct be Initialized this way?
Below is my code, I define a struct containing int
and string
variables.下面是我的代码,我定义了一个包含
int
和string
变量的结构。 I remembered that In c/c++, struct can be initialized like this A a={0}
, And I do this below, However, When I print out its string member b.我记得在 c/c++ 中,struct 可以像这样初始化
A a={0}
,我在下面这样做,但是,当我打印出它的字符串成员 b 时。 program crashed with terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid
.抛出
'std::logic_error' what(): basic_string::_M_construct null not valid
的实例后,程序因调用终止而崩溃。 But if I changed string b to int b,It does not crash any more.但是如果我将字符串 b 更改为 int b,它就不会再崩溃了。 Does anyone know the reason??
有谁知道原因吗??
struct example
{
int a;
string b;
};
int main()
{
example q={0};
cout<<q.b<<endl;
}
Your code is working fine, check the execution here .您的代码运行良好,请在此处检查执行情况。 Your, output will be empty as, strings in c++ is by default empty ie by default size of strings in c++ is 0. So, no output.
Your, output will be empty as, strings in c++ is by default empty ie by default size of strings in c++ is 0. So, no output.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.