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 数组
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
