dpr*_*tch 0 c++ pass-by-reference
在第57页的Koenig和Moo的Accelerated C++一书中,它们提供了如下所示的函数,它返回in.这样做的原因是指示尝试输入是否成功(第55页).但是,in作为函数的参数之一被引用传递.那么你不能通过查看原始对象来获得istream的状态吗?
// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
if (in) {
// get rid of previous contents
hw.clear();
// read homework grades
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}
Run Code Online (Sandbox Code Playgroud)
它允许你组成流畅的界面,像这样
read_hw(cin, hw).read_something_else(cin, x).blah_blah(cin, y)
Run Code Online (Sandbox Code Playgroud)
由于每个方法调用都返回对该istream对象的引用,因此它可用于链接方法调用.
事实上,当你这样做时会发生什么
cin >> a >> b;
Run Code Online (Sandbox Code Playgroud)
每个operator>>函数调用都返回对流的引用,因此可以对其进行链接.
它也可以让你循环并从在读取istream对象用C惯用的方式++,例如
while (read_hw(cin, hw)) {
do_something_with_hw(hw);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |