Overriding static members and “static static array

2019-09-03 17:11发布

问题:

I've got a tricky issue with "overriding" static arrays. I've got static arrays (for simplicity) that are of fixed length in different derived classes, but still all sizes are known in compile-time. I've also got a virtual function in the base class, but I don't know how to tackle the problem of overriding these arrays and array-sizes in the derived classes so that this virtual function works correctly, i.e. gives the sizes and array contents from the derived classes. Example:

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
}

Could you suggest a fix or a different way of doing this correctly? I think std::vector would do it (?), but needs much work to adapt to my existing code. Many thanks, Peter

回答1:

Since f is only defined in the Base class, it will use that class' n variable.

Perhaps move:

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

To a separate function, but instead have it so you pass in what "n" is. like

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

And have each subclass implement f() to call doStuff(n) where n will be each class' own n variable.



回答2:

You could use the Curiously Recurring Template Pattern to make your function access the static array in the most-derived class.