简体   繁体   中英

How to overload operator= to return pointer to a member?

Having something like the following code (simplified):

struct MyStruct {
    int member1;
    int member2;
};

class MyClass { 
    MyStruct *data;
}


MyClass obj;

// put obj.data in pstruct  
// so obj.data->element1 is the same as pstruct->element1
MyStruct *pstruct = obj;

I don't want to create a copy of obj.data but return the same pointer so if i make a change in pstruct->member1 the change is the same in obj.data->element1 (and the opposite).

Is this possible?

Thanks

Sounds like you want a conversion operator that creates a MyStruct* from a MyClass :

class MyClass {
    MyStruct *data;
public:
    operator MyStruct*() {
       return data;
    }
};

No problem.

MyClass obj;

MyStruct *pstruct = obj.data;

The first thing is that you cannot overload operators for pointers, the good thing is that you don't need to, you just need to assign pointers appropriatedly:

MyClass obj;
MyStruct *pstruct = obj.data; // Assuming that `data` is accessible here

If you don't have access to the internal data member, you will need to either provide access (a member function that returns the pointer --breaks encapsulation), or make the calling code a friend of MyClass to grant access to the internal type (still breaks encapsulation, just a bit less).

You can do what you want with a conversion operator, but I'd prefer to see you write a getter method . This avoids issues with implicit conversions.

class MyClass {
private:
    MyStruct *data;
public:
    MyStruct* GetData() const { return data; }
};


int main () {
  MyClass obj;
  MyStruct *pstruct = obj.GetData();
  MyStruct *pstruct2;
  pstruct = obj.GetData();
}

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