b = a++ 相当于 b = a, a = a + 1
b = ++ a 相当于a = a +1, b = a
为什么a++不能做左值
a++返回的是自身的值副本,所以不能作为左值
int int::operator++(int)
{
int oldvalue = *this;
++*this;
return oldvalue;
}
++a 返回的是a加1后自身的引用
int& int::operator ++()
{
*this = *this+1;
return *this;
}
一个令人惊讶的程序:给函数的返回值赋值
这个例子来自《C++ Primer(第四版)》。
- //例程2:给函数的返回值赋值
- #include <iostream>
- #include<string>
- using namespace std;
- char &get_val(string &str, string::size_type ix)
- {
- return str[ix];
- }
- int main()
- {
- string s("a value");
- cout<<s<<endl; //输出 a value
- get_val(s,0)='A'; //函数调用一般是不能作为赋值运算的左值的,但这儿居然没有错,只因为返回值为引用
- cout<<s<<endl; //输出为 A value,不可思议的改变
- system("pause");
- return 0;
- }
正如注释中所讲,返回值为引用,函数调用get_val(s,0)居然可以作为赋值表达式的左值,就这样,其引用的空间(s[0])中所存储的字符被赋值为‘A’,“引用是被返回元素的同义词”,此处完全等同于s[0]='A'。
程序从语法上讲没有问题,运行结果也达到了举例的目的。本例仅在于展示这种用法,理解引用作为函数返回值。在工程中,这种风格的程序当然不推荐使用,当不希望引用返回值被修改时,将返回值声明为const,即:
const char &get_val(string &str, string::size_type ix)