简体   繁体   中英

How to change a class member in a method declared as const

I have a class which gives value for a corresponding time. I have a method that changes the m_time (in hh,mm,ss)[ms] but is declared as const at the end. So I need to change the attribute m_time but I can't ! how could I possibly go around this?

Here is my code:

class CMeasurementValue
{
private:
    double m_value;
    unsigned int m_time;

public:
    CMeasurementValue(double value=0,unsigned int time=0);
    CMeasurementValue(double value,unsigned int hh,unsigned int mm , double ss);
    double getValue() const ;
    unsigned int getTime() const;
    void calculateTime(unsigned int& hh , unsigned int& mm , double& ss ) const;
    bool operator <(const CMeasurementValue& rop)const ;
    friend ostream& operator <<( ostream& out, const CMeasurementValue& rop);
    void print();
};

void CMeasurementValue::calculateTime(unsigned int& hh , unsigned int& mm , double& ss) const
{
    // ??
}

You can declare your member m_time mutable like this:

class CMeasurementValue {
private:
    double m_value;
    mutable unsigned int m_time;
    // ...
};

From the docs:

  • mutable - permits modification of the class member declared mutable even if the containing object is declared const.

However, if the function calculateTime , which is marked as const , is supposed to change the state of one of the members, why is it then marked as const ?

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