覆盖静态成员和“静态静态数组". [英] Overriding static members and "static static arrays"

查看:132
本文介绍了覆盖静态成员和“静态静态数组".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

覆盖"静态数组有一个棘手的问题.我已经得到了静态数组(为简单起见),它们在不同的派生类中的长度是固定的,但是所有大小在编译时都是已知的.我在基类中也有一个虚函数,但是我不知道如何解决在派生类中覆盖这些数组和数组大小的问题,以便该虚函数可以正常工作,即给出大小和数组派生类中的内容.示例:

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
}

您是否可以提出解决方法或正确执行此方法的其他方法?我认为std :: vector可以做到(?),但需要大量工作来适应我现有的代码. 非常感谢, 彼得

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

推荐答案

您可以使用Curiously Recurring Template Pattern来使函数访问派生程度最高的类中的静态数组.

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

这篇关于覆盖静态成员和“静态静态数组".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆