我的问题:
如果我在基类中为 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 ) {}
};
- 我可能可以在基础头文件中定义不同的常量数组, 在派生类中使用定义并选择两个数组之一 那个……但这看起来很尴尬。
- 我可以在基类中设置不同的静态常量数组(这样所有数组在基类中总是可用的),有一个数组,并在派生类中使用枚举来选择基类。
有什么好的解决方案吗?
注意:派生类最终会有不同实现的纯虚函数,所以我想要一个抽象基类
更新,关于评论
- 如上所述,它不一定是有效的 c++(如果声明
static uint32_t m_arr[]
并适当定义,g++ 会编译)。该示例应仅显示我要实现的目标 - 我认为如果不使用c++11,我就不能使用构造函数来初始化数组;数组也很大,在 ctors 中,我宁愿引用在其他地方定义的 const 数组以保持干净的外观
- 我想要数据
const
并且在 ROM 中,最好不要在构造时复制。如果std::vector
可以做到这一点,有人可以很快详细说明一个例子吗?好像是……喜欢here , 我猜。不过,对于具有 const 数据(结构)的大数组,我更愿意将值放在其他地方而不是 ctor 中。
最佳答案
好久没用了,反正下面是我最后用到的。
- 它做我想做的事——避免堆和运行时初始化。一切都是
const
- 我使用了一个额外的成员 - 包含
sizeof
的常量值
代码:
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;
}
关于c++ - 使用 const 值数组初始化基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506230/