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 数组


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01