2016-10-22 77 views
1

我正在製作一個名爲Magick的基於文本的冒險遊戲。
在這場比賽中我有一個類標記damageSpell它看起來像這樣當試圖打印向量元素時,'operator <<'不匹配

class damageSpell { 
    public: 
     int damage; 
     SubClasses type; 
     int manaCost; 
     std::string spellDescription; 
}; 

我後來就用這個類作爲類型的載體,像這樣

std::vector<damageSpell> damageSpells

,我嘗試添加通過使用矢量上的insert函數將一個元素插入到我的damageSpells向量中。

damageSpell fireball; 

user.damageSpells.insert(user.damageSpells.begin(), 0, fireball); 

然後試圖將其打印出來

std::cout << user.damageSpells[0];

一旦這樣做,我收到此錯誤

magick1.cpp:252:15: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘damageSpell’)

我新的C++,而且不知道這意味着什麼或如何我應該去解決它,任何和所有的幫助將不勝感激。

+0

[運算符重載](http://stackoverflow.com/questions/4421706/operator-overloading)將提供信息,特別是關於「Bitshift運算符」的選定答案部分。 – WhozCraig

+0

使用'<<'運算符輸出不是自動發生的。相反,有'''運算符的特殊重載處理每個標準類型的輸出。如果你想用輸出操作符輸出你自己的結構,你需要編寫你自己定製的'operator <<'函數。幾乎所有[良好的初學者書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)將教你如何做到這一點。 –

+0

你認爲在矢量中放入東西會使它不可打印嗎?也許忘記矢量並嘗試打印'damageSpell'對象? – juanchopanza

回答

3

user.damageSpells[0]是你spellDamage類的一個實例。你的編譯器不知道如何打印它。您必須定義一個函數,該函數將在<<運算符上調用並將打印出來。

此運算符重載可以定義是這樣的:

std::ostream& operator<<(std::ostream& stream, const damageSpell& damageSpellToPrint) 
{ 
    // Your code here 
} 

eachtime使用之間的std::ostream(如std::cout)和你的類的實例<<操作將被調用。例如,下面的代碼會直接打電話給你的操作功能,通過std::coutstream參數和user.damageSpells[0]damageSpellToPrint參數:

std::cout << user.damageSpells[0]; 

我建議你this postthis documentation,這將有助於你瞭解C運算符重載的概念++。

+0

好吧,我開始明白這一點,因爲我創建了一個類,所以我必須創建自己的操作符,但一旦創建它,​​我將如何訪問它?我會在使用新操作符後使用哪些代碼 –

+0

@Alice每次在任何'std :: ostream'和類的實例之間使用'<<'時,都會調用您的操作符。 – Aracthor

+0

好吧..忘了它。那麼上面那個函數裏面會有什麼代碼呢?或者什麼樣的代碼,而是。 –

0

您所做的事是打印整個對象,但是< <運算符沒有被定義爲打印任何對象,您必須自己做。 試試這個, std::cout<<user.damageSpells[0].damage<<user.damageSpells[0].manaCost

等等...... 和子太