[英]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.