静态成员变量在基本和派生类中具有相同名称

Static member variables with same name in base and derived classes

本文关键字:变量 派生 静态成员      更新时间:2023-10-16
class Base {
   static std::vector<std::string> filter;
   virtual bool check() {
      if(std::find(filter....))
   }
}
class Derived : public Base {
   static std::vector<std::string> filter;
   bool check() override {
      if(std::find(filter....))
   }
}

假设两个静态变量均在其各自的翻译单元中定义。

我有一个静态字符串的向量,在基础和派生类中带有相同名称,因为它们旨在携带相同类型的信息,而每个类别的值不同。我知道隐藏非虚拟功能的名称不是一个好主意。同样的适用于静态成员变量吗?如果是这样,替代方案是什么?

是的

我将假设check()衍生的覆盖在文本上与基础相同。

您可以使用静态当地人的虚拟方法

class Base 
{
    // ...
    virtual /*const?*/ std::vector<std::string> & filter() 
    {
        static std::vector<std::string> value = ...
        return value;
    }
    bool check() // final
    {
        if(std::find(filter()...))
    }
}
class Derived : public Base
{
    /*const?*/ std::vector<std::string> & filter() // override
    {
        static std::vector<std::string> otherValues = ...
        return otherValues;
    }
}