通常用于普通变量的方法(在成员函数之外声明和在成员函数内初始化)不起作用,因为引用变量需要初始化并在同一行中声明。
#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;
}
发布于 2021-05-26 19:28:21
我想这是你能做的最好的了。
#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;
}
引用是一个常量--它指的是对象整个生命周期中相同的整数。这意味着你需要把它设置在建筑上。
发布于 2021-05-26 19:32:24
如何在成员函数中初始化引用成员变量&在其他成员函数中访问它- 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;
}
发布于 2021-05-26 19:30:52
int var; int& varref = abc::var;
这应该管用!
https://stackoverflow.com/questions/67711456
复制相似问题