2015-12-15 87 views
1

我有以下代碼:我不知道問題是什麼。它強調了for循環中的cout之後的'< <'。列表迭代器錯誤C++

#include <fstream> 
#include <sstream> 
#include <ostream> 
#include <istream> 
#include <string> 
#include <iostream> 

#include <iterator> 
#include <list> 

list<weatherStation> station; 
weatherStation *aStation; 

aStation = new weatherStation(); 

for (list<weatherStation>::iterator it = station.begin(); it != station.end(); ++it) 
     { 
      cout << *it << endl; 
     } 

我發現了錯誤是:

錯誤2錯誤C2679:二進制「< <」:沒有操作員發現它採用類型「氣象站」的 右邊的操作數(或沒有可接受的 轉換)\ zorak2 \用戶$ \ s0941625 \我的文檔\ Visual Studio的 2013 \項目\ lentzis \ lentzis \ newmain.cpp 100 1 PROJECT1

3智能感知:沒有運營商 「< <」 這些操作數 操作數類型匹配:性病:: ostream的< <氣象站\ zorak2 \用戶$ \ s0941625 \我的文檔\ Visual Studio的 2013 \項目\ lentzis \ lentzis \ newMain.cpp 101 10 PROJECT1

+0

即時消息不知道你的定義是什麼意思? –

+0

由於沒有定義'weatherStation',所以編譯器不會很快就開始抱怨。 –

回答

2

簡短的回答

weatherStation 

需要通過std::cout進行顯示。一種選擇是定義相應的流運算符作爲friend你的類中:

inline friend 
std::ostream& operator<<(std::ostream& os, const weatherStation& ws) 
{ 
    os << weatherStation.some_member; // you output it 
    return os; 
} 

龍答案

的顯示問題在C經常發生的問題++。將來可以做的是定義一個抽象類,我們將其稱爲IDisplay,它聲明純虛函數std::ostream& display(std::ostream&) const並聲明operator<<爲朋友。然後,每個想要顯示的課程都必須從IDisplay繼承,並因此實施display成員函數。這種方法重用了代碼,非常優雅。下面的示例:

#include <iostream> 

class IDisplay 
{ 
private: 
    /** 
    * \brief Must be overridden by all derived classes 
    * 
    * The actual stream extraction processing is performed by the overriden 
    * member function in the derived class. This function is automatically 
    * invoked by friend inline std::ostream& operator<<(std::ostream& os, 
    * const IDisplay& rhs). 
    */ 
    virtual std::ostream& display(std::ostream& os) const = 0; 

public: 
    /** 
    * \brief Default virtual destructor 
    */ 
    virtual ~IDisplay() = default; 

    /** 
    * \brief Overloads the extraction operator 
    * 
    * Delegates the work to the virtual function IDisplay::display() 
    */ 
    friend inline 
    std::ostream& operator<<(std::ostream& os, const IDisplay& rhs) 
    { 
     return rhs.display(os); 
    } 
}; /* class IDisplay */ 

class Foo: public IDisplay 
{ 
public: 
    std::ostream& display(std::ostream& os) const override 
    { 
     return os << "Foo"; 
    } 
}; 

class Bar: public IDisplay 
{ 
public: 
    std::ostream& display(std::ostream& os) const override 
    { 
     return os << "Bar"; 
    } 
}; 

int main() 
{ 
    Foo foo; 
    Bar bar; 
    std::cout << foo << " " << bar;  
} 

Live on Coliru