2017-12-18 170 views
0
#include<iostream> 
    #include <conio.h> 
    using namespace std; 

    struct book 
    { int bookid; 
     char title[20]; 
     float price; 
    }b2; 

int main() 
    { 
    b2={100,"c++ by saurabh",105.2}; //values initialised during variable declaration 

    cout<<"\n"<<b2.bookid; 
    cout<<b2.title<<" "<<b2.price; 
    return 0; 
    getch(); 
    } 

這上面的代碼顯示在輸出誤差這樣的:敵不過「運算符=」(操作數的類型是「書」和「<大括號包圍的初始化列表>」)

C:\Users\shandude\Documents\codeblock\cprog\struct2.cpp|13|error: no match for 'operator=' (operand types are 'book' and '')|

C:\Users\shandude\Documents\codeblock\cprog\struct2.cpp|5|note: no known conversion for argument 1 from '' to 'const book&'|

+0

你覺得'b2 = {100,「C++ by saurabh」,105.2}; '應該這樣做? – Galen

+0

關閉主題,但最後兩行'return 0;'和'getch();'應該顛倒過來。 'getch();'什麼都不做。應用程序將在此行被調用之前返回。另外:在全局範圍內使用名稱空間標準不是一個好主意,也不是好的做法。 –

+0

應該編寫_initialize_'b2'(創建'b2'的一部分)還是給'b2(創建後的值)賦一個值? – chux

回答

0

什麼你正在做的不是初始化,而是分配,因爲b2已經在早些時候宣佈。您需要在變量聲明點初始化:

struct book 
    { int bookid; 
     char title[20]; 
     float price; 
    } b2 = {100,"c++ by saurabh",105.2}; //values initialised during variable declaration 

int main() 
{ 
    cout<<"\n"<<b2.bookid; 
    cout<<b2.title<<" "<<b2.price; 
    return 0; 
    getch(); 
} 
1

您可以使用:

b2 = book{100,"c++ by saurabh",105.2}; 

PS

我將建議改變成員變量titlestd::string。使用char陣列來表示用戶代碼串是在2017年

struct book 
{ 
    int bookid; 
    std::string title; 
    float price; 
}; 
+0

1998年已經不是時代錯誤了嗎? ;) – Quentin

-1

您正試圖通過list initialization初始化b2不合時宜。您可以閱讀reference以瞭解如何對其進行初始化。
有很多方法。一個簡單的方法是:

book b2{100,"c++ by saurabh",105.2}; 
+2

'b2'已經存在。代碼試圖*分配給它,這是不同的初始化 –

+0

你的解決方案給了我確切的答案我究竟在哪裏我困惑,非常感謝你。 – shandude

0

你使用什麼編譯器?

刪除#include <conio.h>並將float替換爲double後,Clang和VC++都接受此代碼,而GCC抱怨。我認爲這是GCC的一個bug。

雖然這不是初始化,但它等同於將初始化程序列表作爲參數調用賦值運算符。賦值運算符的參數是const book&,並使用此初始化程序列表來初始化此引用已定義良好。該計劃也是明確的。

相關問題