initialize a const array in a class initializer in C++(在 C++ 中的类初始化程序中初始化 const 数组)
问题描述
我在 C++ 中有以下类:
I have the following class in C++:
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
问题是,我如何在初始化列表中初始化 b,因为我无法在构造函数的函数体内初始化它,因为 b 是 const
?
The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const
?
这不起作用:
a::a(void) :
b([2,3])
{
// other initialization stuff
}
典型的例子是我可以为不同的实例设置不同的 b
值,但已知这些值在实例的生命周期内是恒定的.
The case in point is when I can have different values for b
for different instances, but the values are known to be constant for the lifetime of the instance.
推荐答案
正如其他人所说,ISO C++ 不支持.但是你可以解决它.只需使用 std::vector 代替.
Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.
int* a = new int[N];
// fill a
class C {
const std::vector<int> v;
public:
C():v(a, a+N) {}
};
这篇关于在 C++ 中的类初始化程序中初始化 const 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中的类初始化程序中初始化 const 数组


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01