首页 > 其他 > 详细

类引用作为函数返回值的问题

时间:2017-11-04 15:33:42      阅读:354      评论:0      收藏:0      [点我收藏+]

记录自己尝试C++的一点心得

我的第一个尝试其实是如下,

class Object{
public:
 static int r(){
    int i=1;
    return i;
  }
};

int main(int argc, char const *argv[]) {
  int& i=Object::r();
   return 0;
}

报错信息

main.cpp:40:19: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int

在编译的时候就出现问题。引用是变量的别名,而函数返回值在main里是不能改变的,所以需要常引用,const int&才形

然后又试了下如下

class Object{
public:
    static Object&  new_instance(){
    //只能使用非引用的方式将局部对象变量传出去
    Object o;
    return o;
  }
  static int & f(){
    //这里也有上述问题
    int i=1;
    return i;
  }
}
int main(int argc, char const *argv[]) {
  const int& i=Object::f();
   const Object & o=Object::new_instance();
  printf("%d\n",i );
  printf("%d\n",o.i);
}

编译时警告

main.cpp: In static member function ‘static Object& Object::new_instance()’:
main.cpp:17:12: warning: reference to local variable ‘o’ returned [-Wreturn-local-addr]
     Object o;
            ^
main.cpp: In static member function ‘static int& Object::f()’:
main.cpp:22:9: warning: reference to local variable ‘i’ returned [-Wreturn-local-addr]
     int i=1;

运行是会出现段错误,函数内的局部变量是不能作为引用的返回值的。

 

类引用作为函数返回值的问题

原文:http://www.cnblogs.com/Jacket-K/p/7783362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!