#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; }
【C++】 关键字 mutable
最新推荐文章于 2024-07-11 17:21:10 发布