初始化派生类虚函数返回的内联静态变量的最佳方法

最初,我有m_damage作为基类Projectile中的类成员,在每个派生类的初始化列表中分配了值,并且在基类中只有一个getter函数。

But then I realized I dont need every instance of the derived classes holding a copy of m_damage since it was the same value for all instances of each derived class, so I needed to make the value static and have each derived class return it in a virtual function override.

After researching online and on here I believe inline static const variable is the way to go. But is there any benefit to having it as a class member or class constant? or is there another better way to do it? I only want the value accessed via the private virtual function in Projectile.

projectile.h文件

class Projectile
{
private:
    virtual int getDamage() const = 0;
}

火箭.h文件

class Rocket : public Projectile
{
private:
// inline static const auto ROCKET_DAMAGE = 400;  <---- make it a class member?
    virtual int getDamage() const final override;
}

火箭.cpp文件

// inline static const auto ROCKET_DAMAGE = 400;  <---- make it a class constant?

int Rocket::getDamage() const
{
    return ROCKET_DAMAGE;
}
评论
  • 之冰巧
    之冰巧 回复

    This is a good use case for static class variables. If it is a constant, and is the same value for all objects of the class, it will just waste memory if it is a data member. I would go ahead and also make it constexpr so it is allocated at compile-time, and is available for compile-time computation, should you need it (assuming you have a C++17 enabled compiler}:

    constexpr static auto ROCKET_DAMAGE = 400;
    

    解决此问题的另一种方法是不使用静态变量,而是直接从虚拟函数返回值:

    int Rocket::getDamage() const
    {
        return 400;
    }
    

    Using a static class variable will make it slightly easier to change the value in the future, if you need to: it is easier to just modify the header file directly as opposed to trawling through the implementation file and finding the correct function definition. This may be a negative, however, if the header file is #include-d in multiple files, as it will require recompiling all source files with this header, which means longer compile times.