gpt4 book ai didi

c++ - 跟踪 C++ 类中的更改

转载 作者:行者123 更新时间:2023-11-30 00:50:47 25 4
gpt4 key购买 nike

将用一个简单的例子来解释这一点。

class Vector
{
float X;
float Y;
float _length;
float Length();
}

如果 X 或 Y 发生变化,我只会计算长度并将其分配给 _length。如果它们都没有改变,我只是简单地返回 _length。

最佳答案

您需要包含一个保护标志(或“无效”值),您通过以下方式用 X/Y 修改进行标记:

class Vector {
public:
Vector(float x = 0.0, float y = 0.0)
: X{x}, Y{y}, Length{-1.0f}
{ }

float x() const { return X; }
float y() const { return Y; }

float length() const {
if (Length < 0.0f) {
Length = sqrt(X*X + Y*Y);
}
return Length;
}

void setX(float x) { if (X != x) { Length = -1.0f; } X = x; }
void setY(float y) { if (Y != y) { Length = -1.0f; } Y = y; }

private:
float X;
float Y;
mutable float Length;
};

mutable 限定符意味着这些值不是对象“逻辑”状态的一部分,甚至可以在 Vector< 的 const 实例上修改(当然是通过 const 成员函数)。

关于c++ - 跟踪 C++ 类中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23767873/

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