【问题标题】:Overriding static members and "static static arrays"覆盖静态成员和“静态静态数组”
【发布时间】:2011-05-08 12:50:34
【问题描述】:

我遇到了一个关于“覆盖”静态数组的棘手问题。我在不同的派生类中有固定长度的静态数组(为简单起见),但在编译时仍然知道所有大小。我在基类中也有一个虚函数,但我不知道如何解决在派生类中覆盖这些数组和数组大小的问题,以便这个虚函数正常工作,即给出大小和数组派生类的内容。示例:

class B  {
private:
 // these two are not really meaningful in this class (ABC)
 static const int n = 1;
 static double da[n];
public:

 virtual void f()
 {
  for(int i = 0; i < n; ++i)
  {
   // do something with n and da
   std::cout << n << std::endl;
  }
 }
};

class D1 : public B  {
private:
 // these are subclass-specific (i.e. n might also change)
 static const int n = 4;
 static double da[n];
};

class D2 : public B  {
private:
 // these are subclass-specific (i.e. n might also change)
 static const int n = 6;
 static double da[n];
};


double D1::da[] = {1., 2., 3., 4.};
// ...

int main()
{
 B *p = new D;
 p->f(); // I'd like to see 4 instead of 1
}

您能否建议一种修复方法或另一种正确执行此操作的方法?我认为 std::vector 会做到(?),但需要做很多工作来适应我现有的代码。 非常感谢, 彼得

【问题讨论】:

    标签: c++ arrays inheritance static virtual


    【解决方案1】:

    您可以使用奇怪循环模板模式让您的函数访问最派生类中的静态数组。

    【讨论】:

    • 非常感谢,我按照您的建议尝试了这个,它按预期工作。不幸的是,我希望能够在 B 接口上使用动态多态性,我认为这是不可能的。还是这样?
    【解决方案2】:

    由于 f 仅在 Base 类中定义,因此它将使用该类的 n 变量。

    也许移动:

    for(int i = 0; i < n; ++i) 
      { 
       // do something with n and da 
       std::cout << n << std::endl; 
      }
    

    到一个单独的函数,但是有它,所以你传递“n”是什么。喜欢

    void doStuff(int num) {
        for(int i = 0; i < num; ++i) 
        { 
          // do something with n and da 
          std::cout << num << std::endl; 
        }
    }
    

    并让每个子类实现 f() 来调用 doStuff(n) 其中 n 将是每个类自己的 n 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2014-04-14
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多