首页 > 解决方案 > 在 C++ 中的引用变量中输出

问题描述

我正在学习 C++ 中的引用变量。

#include<iostream>
using namespace std;
int &fun()
{
    static int z = 10;  
    return z;
}                       
int main()
{                                      
    int x = fun();
    cout<<fun()<<endl;
    x = 30;
    cout<<fun();
    return 0;
}

为什么这段代码给 10 10 而不是 10 和 30。

标签: c++referencepass-by-reference

解决方案


fun返回一个z为 10 的引用。

您的代码基本上等同于:

int *fun()
{
    static int z = 10;  
    return &z;
}                       
int main()
{                                      
    int x = *fun();
    cout << *fun() << endl;
    x = 30;
    cout << *fun();
    return 0;
}

如果您想获得您期望的行为,您也需要声明x为参考:

int & x = fun();

这说明了它:

using namespace std;
int & fun()
{
  static int z = 10;
  cout << "z = " << z << endl;
  return z;
}
int main()
{
  int & x = fun();
  cout << fun() << endl;
  x = 30;
  cout << fun();
  return 0;
}

推荐阅读