c++ - 在 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。
解决方案
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;
}
推荐阅读
- react-native - 如何隐藏屏幕标题但显示后退按钮?
- django - 如何根据 django 模型/字典向日期时间列添加周数?
- java - 选择底部导航选项卡时重叠的片段
- apache-kafka - 如何跟踪来自多个主题的 Kafka 消息的生命周期?
- video - 视频未在灯箱的弹出框中播放
- c# - 使用默认路径处理自定义错误在 c# Webconfig 中不起作用?
- php - Laravel 关系查询加载 hasMany + BelongsToMany
- python - 如何解决 AssertionError: Context 必须先在 Tensorflow 中初始化
- pyspark - 从 pyspark 中的两个数据框列创建新的元组列的问题
- c# - 将复杂对象列表与另一个复杂对象列表排序 C#