首页 > 解决方案 > 如何在成员函数中初始化引用成员变量并在其他成员函数中访问它 - 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++

解决方案


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

推荐阅读