简体   繁体   中英

How to initialize a reference member variable inside a member function & access it inside other member functions - C++

The usual method one'd use for normal variables (declaring outside the member functions & initializing inside a member function) doesn't work, as reference variables need to be initialized & declared in same line.

#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;
}

How to initialize a reference member variable inside a member function & access it inside other member functions - C++

Use a pointer.

#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;
}

I think this is the best you can do.

#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;
}

A reference is a constant thing — it refers to the same integer for the entire lifespan of the object. That means you need to set it on construction.

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

This should work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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