C++ const in getter

前端 未结 5 1425
鱼传尺愫
鱼传尺愫 2021-01-30 22:55

I\'m still learning about C++ and I\'m reading everywhere that I have to use const everywhere I can (for speed reason I think).

I\'m usually write my getter

5条回答
  •  忘了有多久
    2021-01-30 23:42

    A const getter has the signature

    bool getReady() const
    

    The other version isn't a const method, it just returns a const value (which is basically useless).

    Having a const getter allows you to call it on const objects:

    const Object obj;
    obj.getReady();
    

    This is only valid if getReady is marked as const.

提交回复
热议问题