2015-12-15 3 views
1

У меня есть следующий код: im не уверен, в чем проблема. Он подчеркивает '< <' после cout в цикле for.list iterator error 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 IntelliSense: нет оператор "< <" соответствует этим операнды типы операндов: зЬй :: ostream < < метеостанция \ zorak2 \ пользователи $ \ s0941625 \ Мои документы \ Visual Studio 2013 \ Projects \ 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