c++ - 让一个类方法为每个实例保存一个不同的静态变量

标签 c++

所以我的问题是:

我有一个包含 int position 的类,以及一个通过 float move(float dx) 移动实例的方法。但是,我保留余数并将实例从 dx 的整数部分移出。它是这样实现的(这只是一个最小的例子):

#include <algorithm>

class A {
  public:
    A(x): position(x) {}

    void move(float dx) {
        static float remainder{0.f};

        float total_dx = dx + remainder;
        int to_move = std::floor(total_dx);

        position += to_move;
        remainder = total_dx - to_move;
    }

  private:
    int position;
};

我的问题是 A 的每个实例共享 remainder。这个变量只被 move 方法使用,所以把它作为私有(private)成员放在类中感觉不自然(而且不好)。我想知道是否有一种方法可以将变量限制在 move 的范围内,同时让 A 的每个实例都保留其唯一的 remainder

谢谢!

最佳答案

Have a class method hold a different static variable for every instance

void move(float dx) {
    static std::map<A*, float> remainder;

    float total_dx = dx + (remainder.count(this) ? remainder[this] : 0.f);
    int to_move = std::floor(total_dx);

    position += to_move;
    remainder[this] = total_dx - to_move;
}

如果您想将 remainder 与类 A 分离并将其访问权限限制为仅 move() 函数,则可以这样做。但是请注意,如果将对象保存在动态容器中或重新分配给新对象(如果旧对象已被删除),则对象的地址可能会发生变化。如果您的应用程序存在这种风险,则应在构造函数中分配一些唯一的 id,但您最终会得到 id 成员而不是 remainder 成员,这似乎毫无意义。

关于c++ - 让一个类方法为每个实例保存一个不同的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58400501/

相关文章:

c++ - 虚拟机中的OpenGL问题

c++ - C++ 中的常量混淆

c++ - std::is_same 和 std::get 在一起

时间:2018-03-08 标签:c++opengl: how can i combine 2 different projection types for 3d graphics and 2d menus?

c++ - 数据写入磁盘回调

c++ - 使用大于为 src 分配的内存的计数调用 memcpy 是否安全?

c++ - 使用文件输入运行 C++ 的命令

c++ - 在 C++ 中构造 XML

c++ - Boost asio ip tcp iostream 错误检测

python - 从 C++ 运行 python 脚本