[英]list iterator error c++
我有以下代码:我不确定是什么问题。 它在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:二进制'<<':未找到采用'weatherStation'类型的右侧操作数的运算符(或没有可接受的转换)\\ zorak2 \\ users $ \\ s0941625 \\ mydocuments \\ visual studio 2013 \\ projects \\ lentzis \\ lentzis \\ newmain.cpp 100 1 Project1
和
3 IntelliSense:没有运算符“ <<”与这些操作数匹配,操作数类型为:std :: ostream << weatherStation \\ zorak2 \\ users $ \\ s0941625 \\ My Documents \\ Visual Studio 2013 \\ Projects \\ lentzis \\ lentzis \\ newMain.cpp 101 10 Project1
简短答案
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.