C++引用

来源:百度知道 编辑:UC知道 时间:2024/07/01 07:31:25
在VC++6.0上运行,感觉程序没问题,是书本上的,但提示无法传值,什么原因????
程序:
#include<iostream>
using namespace std;
int f(int i)
{ return ++i;
}
int g(int & i)
{ return ++i;
}
int main()
{ int a=0,b=0;
a+=g(g(a));
a+=g(f(b));
cout<<"a="<<a<<" b="<<b<<endl;
return 1;
}
提示:
Compiling...
a.cpp
F:\C C++\ddd\a.cpp(11) : error C2664: 'g' : cannot convert parameter 1 from 'int' to 'int &'
A reference that is not to 'const' cannot be bound to a non-lvalue
F:\C C++\ddd\a.cpp(12) : error C2664: 'g' : cannot convert parameter 1 from 'int' to 'int &'
A reference that is not to 'const' cannot be bound to a non-lvalue
执行 cl.exe 时出错.

a.obj - 1 error(s), 0 warning(s)

函数g和f返回的不是一个常量,所以不能用&取地址!
#include<iostream>
using namespace std;
int f(int i)
{
return ++i;
}
int g(int &i)
{
return ++(i);
}
int main()
{
int a=0,b=0;
int c = g(a);
a += g(c);
int d =f(b);
a += g(d);
cout<<"a="<<a<<" b="<<b<<endl;
return 1;
}

将函数的返回值作为实参,其间会有匿名变量参与,看下面的调用你会更清楚:
a += g(1+2); // 会报同样的错,匿名变量只允许会常引用
你不能改变g()的返回值,亦如你不能改变(1+2)这个表达式的返回值一样
如果按下面的方法改一下,可以通过其中一句
int& g(int &i) { return ++i;}

a+=g(f(b)); 这句话有错误,b是把它的值传递给f函数,它返回的也只是一个值,赋给一个临时变量,用f()表示,这个临时变量把值传递出去后就被销毁,你却把它当成g()函数的实际参数,使用了引用语句,而且你用一个变量去引用常量,自然会发生错误
你可以选择先定义一个变量c,先把c=f(b);然后用c替换a+=g(f(b))中的f(b) 这样应该就没错了