- 论坛徽章:
- 1
|
ctsweeper 发表于 2012-07-18 18:50 ![]()
我的疑问是:什么情况下函数的返回值又被当做左值的需求呢? 从The C++ Programming Language 3rd Edition上面借来的一个例子。
返回值为坐值的需求的时候。- #include <iostream>
- #include <vector>
- using namespace std;
- struct word {
- string name;
- int count;
- };
- vector<word> vWords;
- int& value(const string& s)
- {
- for (int i = 0; i < vWords.size(); i++)
- if (s == vWords[i].name)
- return vWords[i].count;
- word p = { s, 0 };
- vWords.push_back(p);
- return vWords[vWords.size()-1].count;
- }
- int main(void)
- {
- string buf;
- while (cin >> buf)
- value(buf)++;
- for (vector<word>::const_iterator p = vWords.begin();
- p != vWords.end(); p++)
- cout << p->name << ": " << p->count << '\n';
- }
复制代码 |
|