我试图理解这个陈述:
int main() {
fstream inf( "ex.txt", ios::in );
char c;
while( inf >> c ) {
cout << c << ", ";
}
return 0;
}
在上面的while循环中,(inf >> c)返回什么?我下载了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' : 必须在构造函数基类/成员初始化列表中初始化
然而,在这种情况下,我真的不知道应该将self_ref初始化为什么?当处理链表时,我理解指向自身的指针,我也知道在C++中引用(&
)只是C中指针的伪装形式。但是我无法解释这种情况?istream
的内部实现是如何工作的?引用如何被评估为true或false?谢谢!
编辑:
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循环中正常工作?