请教C++高手,关于“以定义了<<运算的自定义类来初始化ostream_iterator”的问题

C++Primer第四版说任何定义了<<预算的类型都可以做为参数来初始化ostream_iterator(输出流迭代器),但是我这么写怎么就不行呢?说我不能把CTest的对象转化为ostream的引用,但是我确实定义了<<运算啊

#include <iostream>using namespace std;
#include <iterator>
class CTest
{
public :
int m_nData;

CTest (int nData = 0) : m_nData(nData) {}
CTest& operator << (int nData)
{
m_nData = nData;
return *this;
}
};

int main ()
{
CTest test;
ostream_iterator<int> oiit(test);//这行报错,说不能把CTest转化成ostream的引用
return 0;
}

LZ你可能理解错了。并不是任何定义了<<预算的类型都可以做为参数来初始化ostream_iterator(输出流迭代器)。应该是只有basic_ostream和继承了这个类的类才能当作参数来初始化ostream_iterator。可能因为以上类型基本都重载了<<,所以LZ才搞错了吧。

最常用的basic_ostream类型的变量其实就是cout
以下就是MSDN中的范例

// ostream_iterator_ostream_iterator.cpp
// compile with: /EHsc
#include <iterator>
#include <vector>
#include <iostream>

int main( )
{
using namespace std;

// ostream_iterator for stream cout
ostream_iterator<int> intOut ( cout , "\n" );
*intOut = 10;
intOut++;
*intOut = 20;
intOut++;

int i;
vector<int> vec;
for ( i = 1 ; i < 7 ; ++i )
{
vec.push_back ( i );
}

// Write elements to standard output stream
cout << "Elements output without delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( cout ) );
cout << endl;

// Write elements with delimiter " : " to output stream
cout << "Elements output with delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( cout, " : " ) );
cout << endl;
}

这是输出
10
20
Elements output without delimiter: 123456
Elements output with delimiter: 1 : 2 : 3 : 4 : 5 : 6 :

同样
任何一个ofstream或支持写的fstream类型也能当ostream_iterator的参数。
比如将上面的范例稍加修改:

// ostream_iterator_ostream_iterator.cpp
// compile with: /EHsc
#include <iterator>
#include <vector>
#include <fstream>
int main( )
{
using namespace std;
ofstream file("test.txt"); //用ofstream类型的file代替了cout
ostream_iterator<int> intOut ( file , "\n" );
*intOut = 10;
intOut++;
*intOut = 20;
intOut++;
int i;
vector<int> vec;
for ( i = 1 ; i < 7 ; ++i )
{
vec.push_back ( i );
}
// Write elements to standard output stream
file << "Elements output without delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( file ) );
file << endl;
// Write elements with delimiter " : " to output stream
file << "Elements output with delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( file, " : " ) );
file << endl;
}

运行后会生成一个test.txt文件。内容为:
10
20
Elements output without delimiter: 123456
Elements output with delimiter: 1 : 2 : 3 : 4 : 5 : 6 :
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-10-12
"流迭代器都是类模板:任何已定义输入操作符(>> 操作符)的类型都可以
定义 istream_iterator。类似地,任何已定义输出操作符(<< 操作符)的类型
也可定义 ostream_iterator。"

应该理解为 作为 i/ostream_iterator模板 的 类型参数
重载的 <<操作符 也是对 相应的流和自定义类型 的重载

你的CTest就是ostream& operator<<(ostream&os,const CTest&t);
ostream_iterator<CTest> oiit(cout);本回答被网友采纳
相似回答