【问题标题】:Can struct be Initialized this way?可以这样初始化结构吗?
【发布时间】:2020-12-07 04:44:38
【问题描述】:

下面是我的代码,我定义了一个包含intstring 变量的结构。我记得在 c/c++ 中, struct 可以像这样A a={0} 初始化,我在下面这样做,但是,当我打印出它的字符串成员 b 时。抛出一个实例后程序崩溃并调用终止 'std::logic_error' what(): basic_string::_M_construct null not valid。但是如果我将字符串 b 更改为 int b ,它不再崩溃了。有谁知道原因吗??

struct example
{
    int a;
    string b;
};

int main()
{
    example q={0};
    cout<<q.b<<endl;
}

【问题讨论】:

标签: c++ class struct initialization


【解决方案1】:

您的代码运行良好,请检查执行here。 您的输出将为空,因为 c++ 中的字符串默认为空,即默认情况下,c++ 中字符串的大小为 0。因此,没有输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2010-09-11
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多