gpt4 book ai didi

c++ - 如何重构 C++ 中的类以使某个函数成为常量?

转载 作者:太空狗 更新时间:2023-10-29 23:38:29 24 4
gpt4 key购买 nike

我有一个看起来像这样的类:

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;
};

因为我是这样设计我的类(class)的,所以我不得不这样做:

MyClass :: myFunction( void ) const
{
if( !loaded )
{
// do something here

loaded = true; /** <-- this violates const **/
}

// carry out some computation
}

因为我需要设置 loaded 标志,该函数现在违反了 const 限定符。

我有很多存储常量对象的代码,将它们更改为非常量会很耗时。此外,这会有点 hacky,因为我真的希望对象是 const。

重构我的类以保持 myFunction 不变的最佳方法是什么?

附言由loaded 保护的资源只有几个功能需要,因此提前加载它们不是一个很好的解决方案。

最佳答案

使用 mutable 关键字。

class MyClass
{
public:
void myFunction( void ) const;
private:
mutable boolean loaded;
};

这表示加载的成员在逻辑上应该被视为常量,但在物理上它可能会改变。

关于c++ - 如何重构 C++ 中的类以使某个函数成为常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com