简体   繁体   中英

C++ return reference of object

    MyClass& getMyClass() {return m_class}

private:

    myClass* m_class;

This gives me error msg: error: invalid initialization of reference of type 'myClass&' from expression of type 'myClass*'

What should I change to make it work? I want to return refenrence of this object. So I dont want to change getMyClass function prototype.

Change it to

return *m_class;

Make sure m_class is a valid pointer (eg not NULL or freed)!

MyClass &getMyClass() { return *m_class; }

Because pointers are not references, and you are returning a pointer, whereas should return a reference. In order to turn a pointer into a reference (in this case), you must de-reference a pointer, for example:

MyClass& getMyClass() {return *m_class}

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