这是从 B. Stroustrup 着的《C++ 程序设计语言》第二版的 10.3.3 Input of User-defined Types 节中摘录的示例。代码很旧,但仍然可以通过微小的更改进行编译。示例:
#include <istream> #include <complex> using namespace std; istream& operator>>(istream& s, complex<double>& a) { // input formats for a complex; "f" indicates a float: // // f // (f) // (f, f) double re = 0, im = 0; char c = 0; s >> c; if( c == '(' ) { s >> re >> c; if( c == ',' ) s >> im >> c; if( c != ')' ) s.clear(ios::badbit); // set state } else { s.putback(c); s >> re; } if( s ) a = complex<double>(re, im); return s; }
Despite the scarcity of error-handling code, this will actually handle most kinds of errors. The local variable
c
is initilized to avoid having its value accidentally'('
after a failed operation. The final check of the stream state ensures that the value of the argumenta
is changed if everything went well.
我未能理解上面强调的短语。
最佳答案
如果 s >> c
失败,则 c
不会被写入。
如果 c
未初始化,则它在测试时保持未初始化 if( c == '(' )
。读取未初始化的 char
导致未定义的行为。
作者正在谈论这种未定义行为可能表现出来的可能方式。
char c = 0;
的建议修复依赖于 s.putback(c);
如果 s
不执行任何操作不是 good()
。这没关系,尽管恕我直言,这样写会更清楚:
char c;
s >> c;
if ( !s )
return s;
然后任何阅读代码的人都可以立即看到它在出现错误时表现正常;而不是必须在函数流中线程化并检查是否没有其他操作会做任何意外的事情。
关于c++ - 作者对用户定义类型的输入的评论是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30563673/