C++ 如何在C++;使某个函数常数?
我有一个类似这样的类:C++ 如何在C++;使某个函数常数?,c++,oop,constants,C++,Oop,Constants,我有一个类似这样的类: class MyClass { public: // some stuff omitted /*** A function which, in itself, is constant and doesn't change the class ***/ void myFunction( void ) const; private: /*** If loaded is true, then internal resources are
class MyClass
{
public:
// some stuff omitted
/***
A function which, in itself, is constant and doesn't change the class
***/
void myFunction( void ) const;
private:
/***
If loaded is true, then internal resources are loaded
***/
boolean loaded;
};
因为我是这样设计我的课程的,所以我不得不这样做:
MyClass :: myFunction( void ) const
{
if( !loaded )
{
// do something here
loaded = true; /** <-- this violates const **/
}
// carry out some computation
}
MyClass::myFunction(void)const
{
如果(!已加载)
{
//在这里做点什么
loaded=true;/**使用mutable关键字
class MyClass
{
public:
void myFunction( void ) const;
private:
mutable boolean loaded;
};
这意味着加载的成员应该被视为逻辑常量,但物理上可能会发生变化。哦,天哪……谢谢。我知道有一个非常简单的解决方案。+1:我从来不知道这一点,但需要它很多次。(我使用慢速指针解决方案[bool*loaded=>指针从不变化,但指针后面的值可以改变。)或脏铸液。