【问题标题】:Output in Reference variable in c++ [closed]C ++中引用变量中的输出[关闭]
【发布时间】:2021-08-21 06:22:36
【问题描述】:

我正在学习 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。

【问题讨论】:

  • 解释为什么你期望 30 作为第二个输出?
  • x 不是参考吗?
  • @Jabberwocky 由于函数返回引用,我们将其更改为 30。所以 z 应该是 30。
  • @Alan Birtles 为什么?
  • 您尚未将其声明为参考

标签: c++ reference pass-by-reference


【解决方案1】:

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;
}

【讨论】:

    【解决方案2】:

    因为变量 'x' 没有引用 'z'

    变量'x'是一个int,fun()返回一个int&,'z'只复制'x'中的值

    如果你想改变fun()中'x'的值,你可以:

    #include<iostream>
    using namespace std;
    int &fun()
    {
        static int z = 10;  
        return z;
    }                       
    int main()
    {                
        //X is a reference to Z          
        int& x = fun(); // auto x = fun();
        cout<<fun()<<endl;
        x = 30;
        cout<<fun();
        return 0;
    }
    

    #include<iostream>
    using namespace std;
    int &fun()
    {
        static int z = 10;  
        return z;
    }                       
    int main()
    {                                      
        int x = fun();
        cout<<fun()<<endl;
        //x = 30;
        //Fun directly returns a reference to Z
        fun() = 30;
        cout<<fun();
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2018-10-03
      • 2014-01-28
      • 2012-10-15
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多