#include <iostream>
#include <cstring>

class CTextBlock
{
public:
    std::size_t length() const;
private:
    char * pText;
    // mutable关键字的作用:可以在const成员函数中修改const成员变量。
    //mutable std::size_t textLength;
    //mutable bool        lengthIsValid;
    std::size_t textLength;
    bool        lengthIsValid;
};

std::size_t CTextBlock::length() const{
    if(!lengthIsValid){
        textLength = std::strlen(pText);
/*
mutable.cpp:16: error: assignment of data-member 'CTextBlock::textLength' in read-only structure
mutable.cpp:17: error: assignment of data-member 'CTextBlock::lengthIsValid' in read-only structure
*/
        lengthIsValid = true;
    }
    return textLength;
}

int main(int argc, char *argv[])
{
    
    return 0;
}

相关文章:

  • 2021-12-30
  • 2021-11-17
  • 2021-06-03
  • 2021-12-28
  • 2021-05-19
猜你喜欢
  • 2022-12-23
  • 2022-03-03
  • 2021-12-30
  • 2021-09-05
  • 2022-12-23
相关资源
相似解决方案