首页  

c++ 返回引用     所属分类 c 浏览量 680
使用引用替代指针,更容易阅读和维护
C++ 函数返回一个引用,与返回一个指针类似

返回引用时,引用的对象不能超出作用域
返回一个局部变量的引用是不合法的
可以返回一个静态变量的引用

返回局部变量引用
warning: reference to stack memory associated with local variable 'a' returned 



#include<iostream>
using namespace std; 
int vals[] = {1, 2, 3};
 
int& getValue(int i) {  
   int& ref = vals[i];    
   return ref;   
}

int& get() {
   int a;
   // warning: reference to stack memory associated with local variable 'a' returned 
   // return a; 
   static int x;
   return x;     
}
 
int main(){
    cout << vals[0] << endl;
    getValue(0) = 7;
    cout << vals[0] << endl;
    get()++;
    cout << get() << endl;
    get()++;
    cout << get() << endl;
    
    get()=9;
    cout << get() << endl;
   
}


上一篇     下一篇
物联网五大核心技术

C++引用

micrometer不同使用方法的性能对比测试

px em rem 区别

常用css样式

物联网架构