带有常量值数组的初始化基类

问题描述 投票:1回答:1

我的问题:

如果我为基类中的const元素提议一个数组,并且在某些派生类中数组值将不同,那么最好的方法是什么?

使用单个值很容易。对于数组,我不知道有什么好的解决方案。

当然,此代码不起作用,它只应演示问题和所需的行为:

class Base1 {
public:
  Base1( uint32_t const arr[] ) : m_arr( arr[] ) {}
  // Base1( uint32_t const val ) : m_val( val ) {}
  void f1() {
    int const size = sizeof( m_arr ) / sizeof( uint32_t );
    for( int idx = 0; idx < size; ++idx ) {
      std::cout << "val: " << m_arr[idx] << std::endl;
    }
  }
private:
  uint32_t const m_arr[];
  // uint32_t const m_val;
};

uint32_t const c_arr_derived1[] = { 1, 2, 3 };

// uint32_t const c_val = 3;
class Derived1 : public Base1 {
public:
  Derived1() : Base1 ( c_arr_derived1 ) {}
  //Derived1() : Base1 ( c_val ) {}
};
  • 我可能可以在基本头文件中定义不同的const数组,在派生类中使用定义,并选择两个数组之一那...但是看起来很尴尬。
  • 我可以在基类中设置不同的静态const数组(因此所有数组在基类中始终可用),拥有它们的数组,并在派生类中使用枚举来选择基中的一个数组课。

有什么好的解决方法吗?

注意:派生类最终将具有具有不同实现的纯虚函数,因此我想要一个抽象基类

有关评论的更新

  • 如上所述,它不一定是有效的c ++(如果声明为static uint32_t m_arr[]并适当定义,则g ++会编译)。该示例将仅显示我要实现的目标
  • 我认为,如果不使用c ++ 11,就无法使用构造函数来初始化数组;数组也很大,在ctor中,我想引用其他地方定义的const数组,以保持外观整洁]
  • 我想要数据const并且在ROM中,并且理想情况下不要在构造时复制。如果std::vector可行,那么有人可以在短期内详细说明一个例子吗?似乎是某事。我想像here。对于具有const数据(结构)的大型数组,我更希望将值放在ctor之外的其他位置。
c++ constructor const
1个回答
0
投票

有一段时间,无论如何,以下是我最终使用的语言。

  • 它做了我想要的-避免堆和运行时初始化。一切都是const
  • 我使用其他成员-包含sizeof的const值

代码:

class Base {
public:
  Base( uint32_t const * arr, uint32_t const sz ) : 
      m_arr( arr ), 
      m_sizeof_arr( sz ) {}

  void work() {
    for( int idx = 0; idx < m_sizeof_arr; ++idx ) {
      std::cout << "val: " << m_arr[idx] << std::endl;
    }
  }
private:
  uint32_t const * m_arr;
  uint32_t const m_sizeof_arr;
};

uint32_t const c_arr_derived1[] = { 1, 2, 3 };
class Derived1 : public Base {
public:
  Derived1() : Base ( 
      c_arr_derived1, 
      sizeof( c_arr_derived1 ) / sizeof( uint32_t )  ) {}
};

uint32_t const c_arr_derived2[] = { 4, 5, 6, 7 };
class Derived2 : public Base {
public:
  Derived2() : Base ( 
      c_arr_derived2, 
      sizeof( c_arr_derived2 ) / sizeof( uint32_t ) ) {}
};

int main() {
  Derived1 d1;
  d1.work();
  Derived2 d2;
  d2.work();
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.