【C++】 关键字 mutable

#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;
}
posted @ 2011-08-28 01:30  visayafan  阅读(480)  评论(0)    收藏  举报