简体   繁体   English

在类成员函数中获取引用,并将其分配给C ++中的类数据成员(引用)

[英]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. 代码下面的WRT,Abc和Xyz是2类。

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.. 我在DoOperation(Xyz&temp)中获得一个引用,并希望将其分配给一个类数据成员,即mem1,以便其他成员函数lile DOOperation_2(),DOOperation_3()等可以使用此引用。

I know we can't declare a reference in C++ without initialization. 我知道如果不进行初始化,就无法在C ++中声明引用。 But how do I handle such a scenario in C++ ? 但是,如何在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 . 正如您正确指出的那样,您需要初始化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 ) 然后,您可以稍后在这种方法中使用mem1 (带有一个不错的assert

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

Note that a reference is very similar to a T* const (const pointer). 请注意,引用与T* const (常量指针)非常相似。 The key differences are outlined nicely in this answer Difference between const. 答案之间的区别很好地概述了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()
     {

     }


};

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

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