列出迭代器错误c ++

时间:2015-12-15 17:23:11

标签: c++ list iterator

我有以下代码:我不确定问题是什么。它强调了'<<<<<<在for循环中的cout之后。

#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:二进制'&lt;&lt;' :找不到哪个运营商需要   'weatherStation'类型的右手操作数(或者没有可接受的   转换)\ zorak2 \ users $ \ s0941625 \ my documents \ visual studio   2013 \ projects \ lentzis \ lentzis \ newmain.cpp 100 1 Project1

  

3智能感知:无操作员“&lt;&lt;”匹配这些操作数                   操作数类型是:std :: ostream&lt;&lt; weatherStation \ zorak2 \ users $ \ s0941625 \ My Documents \ Visual Studio   2013 \ Projects \ lentzis \ lentzis \ newMain.cpp 101 10 Project1

1 个答案:

答案 0 :(得分: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

相关问题