我试图理解这句话:
int main() {
fstream inf( "ex.txt", ios::in );
char c;
while( inf >> c ) {
cout << c << ", ";
}
return 0;
}
什么是(inf >> c
) 在上面的 while 循环中返回?我下载了 gcc 源代码并尝试使用它,但它对我来说太复杂了:(。
我检查了 C++ 参考页,我意识到它返回了对自身的引用:
istream& operator>> (bool& val );
istream& operator>> (short& val );
istream& operator>> (unsigned short& val );
istream& operator>> (int& val );
istream& operator>> (unsigned int& val );
istream& operator>> (long& val );
istream& operator>> (unsigned long& val );
istream& operator>> (float& val );
istream& operator>> (double& val );
istream& operator>> (long double& val );
istream& operator>> (void*& val );
istream& operator>> (streambuf* sb );
istream& operator>> (istream& ( *pf )(istream&));
istream& operator>> (ios& ( *pf )(ios&));
istream& operator>> (ios_base& ( *pf )(ios_base&));
*** the following functions are not members but GLOBAL functions:
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signed char& ch );
istream& operator>> (istream& is, unsigned char& ch );
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signed char* str );
istream& operator>> (istream& is, unsigned char* str );
所以我创建了一个类似的类,比如说 my_istream:
struct my_istream {
my_istream& self_ref;
};
int main() {
my_istream mis;
}
编译时,我收到此错误:
1>c:\users\chan\documents\visual studio 2010\projects\topcoder\topcoder\main.cpp(26): error C2758: 'my_istream::self_ref' : must be initialized in constructor base/member initializer list
但是,我真的不知道在这种情况下 self_ref 应该初始化为什么?在处理链表时,我理解指向自身的指针,并且我理解该引用(&
C++中的)只是C中指针的变相形式。但我无法解释这种情况?内部是如何实现的istream
实际上工作吗?如何判断参考文献的真假?谢谢!
EDIT:
struct my_istream {
my_istream() {
}
my_istream& operator >>( int x ) {
return *this;
}
};
int main() {
my_istream mis;
int x;
while( mis.operator>>( x ) ) {
cout << "--";
}
}
我应该向 my_istream 类添加什么才能在 while 循环内工作?