注册 登录
编程论坛 C++教室

引用问题

body202 发布于 2007-10-14 11:50, 393 次点击

下面是用引用编的小程序,问题见程序,请指点
#include <iostream>
using namespace std;
int f(int i)
{
return i++;}
int g(int &i)
{
return i++;}
main()
{
int a=0,b=0,c=0,d=0;
a+=f(g(a));
b+=g(g(b));//请问这个是什么问题呢?提示是不能FROM‘INT’TO‘INT&’
c+=g(f(c));//这个错误同上,应该怎样该才对呢?
d+=f(f(d));
cout<<"a="<<a<<"b="<<b<<"c="<<"d="<<d<<"\n";
return 1;
}


4 回复
#2
zhb_ice2007-10-14 11:58
两个函数返回的都是一个值 不能对某个值进行引用
引用只能对某一个对象

#3
HJin2007-10-14 12:23
回复:(body202)引用问题

#include <iostream>
using namespace std;
int f(int i)
{
return i++;
}

int g(int& i)
{
return i++;
}

int main()
{
int a = 0, b = 0, c = 0, d = 0;

int p, q;

a += f(g(a));

f(5); // work
// g(5); // does not work. A reference needs a LValue, but 5 is an RValue

/**
A refernce is a LValue, which should in general be associated with
a named storage.

g(b) is a RValue.
*/
p=g(b);
b+=g(p);
//b += g(g(b)); //请问这个是什么问题呢?提示是不能FROM‘INT’TO‘INT&’

q =f(c);
c+= g(q);
//c += g(f(c)); //这个错误同上,应该怎样该才对呢?
d += f(f(d));
cout << "a=" << a << "b=" << b << "c=" << "d=" << d << "\n";

return 1;
}

#4
body2022007-10-14 14:28

Good! HJin THANK YOU!

#5
o0花生0o2007-10-16 23:39
这个问题我也不懂,刚好在这里学一下,谢谢楼主,谢谢1楼,谢谢2楼
1