简体   繁体   中英

Get a reference in a class member function & assign it to a class data member (reference) in C++

WRT below code, Abc & Xyz are 2 classes.

I get a reference in DoOperation(Xyz& temp) and want to assign it to a class data member ie mem1, so that this reference can be used by other member functions lile DOOperation_2(), DOOperation_3() etc..

I know we can't declare a reference in C++ without initialization. But how do I handle such a scenario in C++ ?

class Abc
{
public:
    Xyz& mem; //ILLEGAL IN C++
     void DoOperation(Xyz& temp)
     {
        mem = temp;
     }   
     void DOOperation_2()
     {

     }
     DOOperation_3()
     {

     }


};

It's simple: Use a pointer. Unlike references, pointers are assignable.

class Abc
{
public:
     Xyz* mem1;
     void DoOperation(Xyz& temp)
     {
        mem1 = &temp;
     }   
};

As you correctly noted, you need to initialize the reference . You also cannot change what a reference "points" to after it has been initialized .

So the simple solution here is to just use a pointer

class Abc {
public:
    Xyz* mem1{nullptr};
    void DoOperation(Xyz* ptr) {
        mem1 = ptr;
    }
};

And then you can use mem1 later on in a method like this (with a nice assert )

void Abc::SomeMethod() {
    assert(this->mem1);
    mem1->something();
}

Note that a reference is very similar to a T* const (const pointer). The key differences are outlined nicely in this answer Difference between const. pointer and reference?


If you absolutely have to use a reference, the only thing you can do is to initialize a reference in a constructor during initialization.

class Abc {
public:
    Xyz& mem1;
    Abc(Xyz& mem1_in) : mem1{mem1_in} {}
};

Initialize it in constructor:

class Abc
{
public:
    Xyz& mem1;
     Abc (xYZ& temp) : mem1(temp) {} 
// ...
};

or use pointer:

class Abc
{
public:
    Xyz* mem = nullptr;

    void DoOperation(xYZ& temp)
    {
        mem = &temp;
    }
// ...
};

Use a pointer instead.

class Abc
{
public:
     Xyz* mem1; // pointer
     void DoOperation(xYZ& temp)
     {
        mem1 = &temp; // take the address of the variable and save it to the pointer
     }   
     void DOOperation_2()
     {

     }
     DOOperation_3()
     {

     }


};

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