C++ const in getter

前端 未结 5 1424
鱼传尺愫
鱼传尺愫 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:43

    They mean two differnt things:

    const bool isReady() {
        return ready;
    }
    

    This returns a constant bool. Meaning a bool which cannot change value from the time it's been created.

    bool getReady() const { 
        return ready;
    }
    

    This is a a constant function, meaning a function that will not alter any member variables of the class it belongs to. This is the style recommended to use for getters, since their only purpose is to retrieve data and should not modify anything in the process.

提交回复
热议问题