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

有关用引用返回值中的问题??????????????、

芦苇太帅了 发布于 2013-08-30 17:51, 621 次点击
#include<iostream.h>
float temp;

float fn1(float r)
{

    temp=r*r*3.14;
    return temp;
}

float& fn2(float r)
{
    temp=r*r*3.14;
    return temp;
}

int main()
{
    float a=fn1(5.0);
    float& b=fn1(5.0);
    float c=fn2(5.0);
    float& d=fn2(5.0);
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;
    cout<<d<<endl;
}
VC6.0提示:--------------------Configuration: pp193 - Win32 Debug--------------------
Compiling...
ppp193.cpp
F:\C++文件\pp193\ppp193.cpp(7) : warning C4244: '=' : conversion from 'double' to 'float', possible loss of data
F:\C++文件\pp193\ppp193.cpp(13) : warning C4244: '=' : conversion from 'double' to 'float', possible loss of data
F:\C++文件\pp193\ppp193.cpp(20) : error C2440: 'initializing' : cannot convert from 'float' to 'float &'
        A reference that is not to 'const' cannot be bound to a non-lvalue
F:\C++文件\pp193\ppp193.cpp(27) : warning C4508: 'main' : function should return a value; 'void' return type assumed
执行 cl.exe 时出错.

ppp193.obj - 1 error(s), 0 warning(s)
求大神们分析?????????????????????
6 回复
#2
peach54602013-08-30 22:08
我先求你的分析...
你想不动脑子么?那我为什么要告诉你呢?你又不想学...
想学就先自己动脑子分析一下...
#3
芦苇太帅了2013-08-31 11:45
冤枉我了,我试了这种类型的好多程序都是数据类型不能由“DOUBLE”传到“FLOAT”,都提示这种ERROR,所以我没办法了!
#4
peach54602013-08-31 15:12
以下是引用芦苇太帅了在2013-8-31 11:45:19的发言:

冤枉我了,我试了这种类型的好多程序都是数据类型不能由“DOUBLE”传到“FLOAT”,都提示这种ERROR,所以我没办法了!

你怎么试的,说来听听...
今早一起来,就看到你一连发了三四个帖子,,,其他帖子基本都有人回了...基本上都是一些低级错误...


[ 本帖最后由 peach5460 于 2013-8-31 15:13 编辑 ]
#5
hyq17562013-08-31 22:44
“cannot convert from 'float' to 'float &'
        A reference that is not to 'const' cannot be bound to a non-lvalue

关于这句话,我是这样理解的,对函数来说,它并不知道temp是全局的,它不知道在函数结束之后还是否存在temp这个变量,所以不能作为引用返回,是么?
#6
hyq17562013-08-31 23:01
自我感觉自己说的也不是道理,我在想,原因是否是一下几点之一:
1,temp是float变量名,但是引用其实是别名,更像地址,所以不行?
2,temp不可以作为自己自身的引用!是否?
#7
toofunny2013-09-04 01:35
修改如下,编译通过,自己动脑想想有什么不同
#include<iostream.h>
float temp;

float fn1(float r)
{

    temp=r*r*(float)3.14;
    return temp;
}

float& fn2(float r)
{
    temp=r*r*(float)3.14;
    return temp;
}

int main()
{
    float a=fn1(5.0);
//    float& b=fn1(5.0);
    float c=fn2(5.0);
    float& d=fn2(5.0);
    cout<<a<<endl;
//    cout<<b<<endl;
    cout<<c<<endl;
    cout<<d<<endl;
}
1