簡體   English   中英

可以這樣初始化結構嗎?

[英]Can struct be Initialized this way?

下面是我的代碼,我定義了一個包含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;
}

您的代碼運行良好,請在此處檢查執行情況。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM