码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-11-04 16:26:15      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:ddr   别名   ati   bsp   instance   err   val   函数   add   

记录自己尝试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;

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

 

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

标签:ddr   别名   ati   bsp   instance   err   val   函数   add   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!