C++ 引用做函数返回值类型

1)int sum(int a, int b) {int s=a+b; retrun s;}
2)int s;
int sum(int a, int b) { s=a+b; retrun s;}
3)int s;
int & sum(int a, int b) { s=a+b; retrun s;}
4)int& sum(int a, int b) {int s=a+b; retrun s;}
5)int& sum(int a, int b) {int s=a+b; retrun s;}
在主函数中依次根据上面五个函数的格式进行调用,格式如下:
void main() { int & c= sum(2, 3);
cout<< c<<endl;
c = c+10; cout<< c<<endl; }
指出运行结果并说明原因。
新手请教,谢谢!

1.正确,返回值类型
2.正确,s为全局变量,函数中给s赋值。
3.正确,s为全局变量,函数中对s操作,返回全局对象的引用。
4.错误,s为局部变量,函数调用结束后,s被销毁。返回局部对象的引用是错误的。
5.和4不是一样么?

1.2.3输出为
5
15追问

进行调用时是不是这样就行了?
#include
using namespace std;
int sum(int a, int b)
{
int s=a+b;
return s;
}
void main()
{
int &c= sum(2,3);
cout<<c<<endl;
c = c+10;
cout<<c<<endl;
}

追答

为什么要int &c= sum(2,3);
这样是不对的。sum函数返回的是一个值类型。临时对象自带const。如果你要给引用初始化的话
应该是const int &c =sum(2,3);

你这样没什么意义。这个引用你后面也不能做左值。

直接int c=sum(2,3);

追问

哦,其实题目的本意是调用以上函数有些对,有些错,写出错的原因
第一个第二个出现上述报错是什么原因呢?
第三个是对的
第四个是不是就是你回答的s为局部变量,函数调用结束后,s被销毁。返回局部对象的引用是错误的。??

追答

1)int sum(int a, int b) {int s=a+b; retrun s;}
2)int s;
int sum(int a, int b) { s=a+b; retrun s;}

这两个函数这么写是没有错误的。

但是如果你是int &c= sum(2,3);这样的去调用的话,是调用错误。

sum(2,3)可以看成是一个临时变量。临时变量在c++中有const的含义。你不可能把一个const int赋给一个int引用。

追问

谢谢,能加你Q。Q单聊吗?有很多不懂!

追答

私信吧

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-23
关键字都错了..."return"
相似回答