2014-03-28 105 views
2

我寫這些來自書「C++ Programming.Language.4th.Edition」預期初始化之前「和」令牌

#include <ostream> 

struct Entry{ 
    string name; 
    int number; 
} 

ostream& operator<<(ostream& os, const Entry& e){ 
    return os << "{\"" << e.name << "\"," << e.number << "}"; 
} 

int main() 
{ 
    Entry a; 
    a.name = "Alan"; 
    a.number = "12345"; 
    return 0; 
} 

的編譯時錯誤 G ++返回一條錯誤消息一個簡單的例子:預期前「&」令牌

PS初始化:上述&令牌屬於ostream的&操作

會有人提供線索?

+10

'struct'聲明後缺少分號。是的,使用std。 (刪除問題時,你可以:-) – dasblinkenlight

+1

也'INT號碼,然後'a.number =「12345」'是你打算做什麼? – billz

+1

dasblinkenlight是正確的,結構聲明後缺少分號是原因。謝謝! – prgbenz

回答

3

你有四個主要的錯誤:

首先你是結構聲明後失蹤分號。在每一個,classstruct聲明你需要把;

其次ostream不是一個標識符,你可能打算使用std::ostreamostream,位於<ostream>標準標題中,位於std命名空間中。

第三,您缺少std::string標題,您應該參考string類和std::前綴。

最後number是int類型的,而不是const char*類型的文字"12345"是。你可能打算寫:a.number = 12345;

所有這些修訂後,你的程序是這樣的:

#include <ostream> 
#include <string> 

struct Entry{ 
    std::string name; 
    int number; 
}; 

std::ostream& operator<<(std::ostream& os, const Entry& e){ 
    return os << "{\"" << e.name << "\"," << e.number << "}"; 
} 

int main() 
{ 
    Entry a; 
    a.name = "Alan"; 
    a.number = 12345; 
} 

will compile just fine