2015-12-29 83 views
-2

我有一個電影類如方法在頭& CPP:編譯錯誤不能結合 '的std :: basic_ostream <char>' 左值到 '的std :: basic_ostream <char> &&'

movie.h

#include "book.h" 
#include <vector> 

class Book; 
class movie 
{ 
public: 
    movie(string aTitle, int aYear); 
    void fromBook(const Book &b); 
    string toString() const; 

private: 

    std::vector<Book> book; 

}; 

movie.cpp

#include "movie.h" 
#include <sstream> 

    movie::movie(string aTitle, int aYear): 
    title{aTitle}, year{aYear} 
{ 

} 
    void movie::fromBook(const Book &b) 
    { 
     book.push_back(b); 
    } 

    std::string movie::toString() const 
    { 
     stringstream result; 
     result << "\nA film adaption from the book: " << std::endl; 
     for (auto a : book) 
      { 
      result << "\t" << a; 
      if (a != *(book.end()-1)) 
      result << ", "; 
      } 
     return result.str(); 
    } 

出於某種原因,它給我的錯誤:

error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&' 
     result << "\t" << a; 
      ^

雖然我不明白爲什麼。

當使用相同的方法打印一個字符串列表,例如,我沒有得到這個錯誤。

僅供參考:我刪除了不相關的代碼。我只保留任何與書本有關的事情。 (以及原始構造函數)

+1

1)格式化您的代碼。 2)不要瘋狂地混合'std:'和不合格的名字 - 一致地限定所有內容。 3)顯示完整的代碼。 4)您顯示的代碼與錯誤消息不匹配。 –

+0

return(result <<「\ t」<< a);'?你忘了最重要的一段代碼。 – LHLaurini

+0

它呢?在粘貼代碼時會出現一個隨機的「z」,現在編輯它 – aze45sq6d

回答

1

編譯器找不到的Book

發現,如果一個標準庫中

template<class _CharT, class _TraitsT, class _Ty> 
std::basic_ostream<_CharT, _TraitsT>& 
    operator<<(std::basic_ostream<_CharT, _TraitsT>&& _Stream, const _Ty& _Value); 

其中_Ty可能匹配Book,但你的result不是右值等等_Stream參數不匹配的最接近的匹配。不幸的是,這使得錯誤信息不夠清晰。

你應該看到你有一個operator<<Book,並且它在movie.cpp中是可見的。

+0

(回答一個現在已被刪除的評論...)你正試圖將'a'插入到stringstream中,但是編譯器不知道該怎麼做 - 它找不到'<<用於'<< a'。您必須創建一個這樣的操作符,或用'<< a.title << a.author'或'Book'包含的任何字段替換'<< a'。 –

+0

我發現了這個問題,這就是爲什麼我刪除了我的評論。確實是的!你是對的。如果我確實希望能夠調用「<< a」,我可以重載書類中的<<運算符 – aze45sq6d

相關問題