| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1611 人关注过本帖
标题:返回局部对象的引用,小弟遇到问题了!求助
取消只看楼主 加入收藏
独孤剑魔
Rank: 1
等 级:新手上路
帖 子:103
专家分:0
注 册:2008-8-5
收藏
 问题点数:0 回复次数:2 
返回局部对象的引用,小弟遇到问题了!求助
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
const string &ret(string &str1,string &str2)
{
    cout<<"***************************"<<endl;
    cout<<"str1="<<&str1<<endl;
    cout<<"str2="<<&str2<<endl;
    cout<<"str1="<<str1<<endl;
    cout<<"str2="<<str2<<endl;
    if(str1.size()<str2.size())
    {
        str1=str2;
        return str1;
    }
    else
    {
        str2=str1;
        return str2;
    }
}
//测试返回函数内声明对象的引用
int &ret(const int &i,const int &j)
{
    if(i>j)
    {
        int k=i;
        cout<<"&k="<<&k<<"\t"<<k<<endl;
        return k;
    }
    else
    {
        int k=j;
        cout<<"&k="<<&k<<"\t"<<k<<endl;
        return k;
    }
}
string &ret(const string &s)
{
    string str = s;
    return str;
}
int main()
{
    string str1="abcdefg";
    string str2="abcefghigklmn";
    cout<<"str1="<<&str1<<endl;
    cout<<"str2="<<&str2<<endl;
    cout<<"str1="<<str1<<endl;
    cout<<"str2="<<str2<<endl;
    string str3 = ret(str1,str2);
    cout<<"*************************"<<endl;
    cout<<"str1="<<&str1<<endl;
    cout<<"str2="<<&str2<<endl;
    cout<<"str1="<<str1<<endl;
    cout<<"str2="<<str2<<endl;
    cout<<"*************************"<<endl;
    cout<<"str3="<<&str3<<endl;
    cout<<"str3="<<str3<<endl;
    int i=10,j=15;
    int h = ret(i,j);//调用函数,因为返回的是函数中的局部对象的引用,函数执行完时会释放,按说运行时会导致错误。但是此行并没有运行错误?是什么原因啊?
    string aa = "dada";
    string gg = ret(aa);//调用函数,因为返回的是函数中的局部对象的引用,函数执行完时会释放,运行时导致错误。此行就在运行时正常出现错误了,请高手解释下。
    return 0;
}
请各位高手讲讲我注释的第一行,为什么此引用没导致运行时出错。

[[it] 本帖最后由 独孤剑魔 于 2008-9-16 17:04 编辑 [/it]]
搜索更多相关主题的帖子: 局部 对象 
2008-09-16 16:51
独孤剑魔
Rank: 1
等 级:新手上路
帖 子:103
专家分:0
注 册:2008-8-5
收藏
得分:0 
还是上面那个问题,string &ret(const string& s)函数明明需要返回一个string 对象,在main函数中,如果将
string gg = ret(aa)--改为ret(aa);运行时就不会出错,在java中我记得是不可以的,因为需要有相应的类型对象来接受return返回的对象,但是c++中,这样写编译与运行都不会出错了,求教高手把握第一问于第二问一起回答。谢谢了
问题整理:
问题1:请看1楼代码段,加注释地方。
问题2:2楼,上面的那些话,谢谢。
2008-09-16 17:03
独孤剑魔
Rank: 1
等 级:新手上路
帖 子:103
专家分:0
注 册:2008-8-5
收藏
得分:0 
为什么没人回答啊???
2008-09-16 22:47
快速回复:返回局部对象的引用,小弟遇到问题了!求助
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012380 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved