简体   繁体   English

如何更改声明为 const 的方法中的类成员

[英]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.我有一个方法可以改变m_time (in hh,mm,ss)[ms]但最后被声明为const So I need to change the attribute m_time but I can't !所以我需要更改属性m_time但我不能! 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:您可以像这样声明您的成员m_time mutable

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. mutable - 即使包含对象被声明为 const,也允许修改声明为 mutable 的类成员。

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 ?但是,如果标记为const的函数calculateTime应该更改成员之一的状态,那么为什么将其标记为const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM