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; }
指出运行结果并说明原因。
新手请教,谢谢!
进行调用时是不是这样就行了?
#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单聊吗?有很多不懂!
追答私信吧