简体   繁体   中英

How to overload the '->' operator in c++?

I want to write a simple wrapper around another class. A small example:

class MyClass {
   ...
   int someMember();
   ...
};

class MyClassRefernence{
   ...
   MyClass* ptr;
   MyClass& operator *();
   ...
};

If I have now some code like the following:

MyClassReference ref;
... // Init the ref and the pointer ptr.
int a = (*ref).someMember(); // this works but is nasty
int b = ref->someMember(); // Compile error

So my question is: Is there a way to use the much more pretty -> operator instead of the (*...). construction?

MyClass* operator->() { return ptr; }

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