简体   繁体   中英

C++ call reference function from a const pointer

I have a class with this function

class InputState
{
   public:
     key_map const & GetKeyMap();
}

then I have a const pointer:

InputState const * m_pInput;

How can I call that function from m_pInput ?

If your function indeed does not modify the object itself, mark it as const :

 key_map const & GetKeyMap() const;

If it does modify, do not call it from a const pointer (or, well, use const_cast if absolutely needed).

If: your member function doesn't alter the state of the object you add to it the const qualifier:

key_map const & GetKeyMap() const;

Else: use const_cast , which I don't recommend since it would break explicitly the const enss of your pointer, that might be for a reason in the first place:

const_cast<InputState*>(m_pInput)->GetKeyMap();

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