繁体   English   中英

如何在成员 function 中初始化引用成员变量并在其他成员函数中访问它 - C++

[英]How to initialize a reference member variable inside a member function & access it inside other member functions - 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;
}

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

引用是不变的东西——它在 object 的整个生命周期内引用相同的 integer。 这意味着您需要将其设置为构造。

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

这应该工作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM