如何在成员函数中初始化引用成员变量并在其他成员函数中访问它 - 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;
}

我认为这是你能做的最好的。

#include <iostream>
using namespace std;
class abc {
public:
int& var; 
abc(int& temp) :
var(temp)
{}
void fun2 () {cout << abc::var << endl;}
};
int main() {
int y=9;
abc f(y);
f.fun2();
return 0;
}

引用是一个不变的东西——它在对象的整个生命周期中引用相同的整数。这意味着你需要把它设置在建筑上。

int var; int& varref = abc::var;

这应该有效!

最新更新