静态成员变量在基本和派生类中具有相同名称
Static member variables with same name in base and derived classes
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;
}
}
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 继承时如何构建派生类的变量?
- 在派生类中使用基类的私有成员变量的最佳方法
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 如何在C++中找到变量派生最多的子类?
- 从模板化父类中的派生内部类访问受保护的成员变量
- 使用语法公开派生类中的基类别名模板和变量模板?
- 如何将一个变量用于父类和派生类
- C++:使用基类中的仅派生类变量
- 如何根据基类对象中的变量值分配派生类中的变量?
- 如何从派生类访问引用成员变量?
- 为什么基指针可以访问虚拟函数中的派生成员变量
- "Rename"派生类中的成员变量
- OOP - 抽象类类型,初始化基类和派生类中的变量
- 从派生类 c++ 中获取变量
- 如何使黑客合法化,该黑客假定派生的类变量的相邻存储
- 如何从基类向量达到派生的类变量
- C++:使用变量派生.一小部分代码有问题