c++ - 如何在成员函数中初始化引用成员变量并在其他成员函数中访问它 - C++
问题描述
用于普通变量的常用方法(在成员函数外部声明并在成员函数内部初始化)不起作用,因为引用变量需要在同一行中初始化和声明。
#include <iostream>
using namespace std;
class abc {
public:
int& var;
void fun1 (int& temp) {var=temp;}
void fun2 () {cout << abc::var << endl;}
abc() {}
};
int main() {
abc f;
int y=9;
f.fun1(y);
f.fun2();
return 0;
}
解决方案
如何在成员函数中初始化引用成员变量并在其他成员函数中访问它 - C++
使用指针。
#include <iostream>
using namespace std;
class abc {
public:
int* var;
void fun1 (int& temp) { var = &temp; }
void fun2 () { cout << *abc::var << endl; }
abc() {}
};
int main() {
abc f;
int y=9;
f.fun1(y);
f.fun2();
return 0;
}
推荐阅读
- groovy - Soap UI:Groovy 测试步骤:如何从另一个 Groovy 脚本调用 groovy 脚本中的特定方法
- java - 在 jsp 中使用 c:foreach 时如何修复错误 NumberFormatException
- java - Android:Gradle 编译错误期望元素值是一个常量表达式 - 功能模块
- jenkins - Jenkinsfile java.lang.NullPointerException:无法调用方法
在空对象上 - scikit-learn - 保存一个 scikit-learn Bunch 对象
- redis - 如何增加redis中值的大小?
- reactjs - ReactJS:在开发环境中重新加载内部组件时出现 404 错误
- java - 获取整数列表并使用数组反向显示它们
- r - For 循环遍历 data.table 中的列
- mysql - 如何在 MySQL 中使用 sum 函数和 join