在C ++中的类初始化器中初始化一个const数组 [英] initialize a const array in a class initializer in C++
本文介绍了在C ++中的类初始化器中初始化一个const数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C ++中有以下类:
class a {
const int b [2]
//其他的东西如下
//这里是构造函数
a(void);问题是,如何在初始化列表中初始化b,如果初始化列表中没有b,我不能在构造函数的正文中初始化它,因为b const
?
不工作:
a :: a(void):
b([2,3])
{
//其他初始化资料
}
in是指我可以为不同的实例具有不同的 b
值,但是这些值在实例的生命周期中是已知的。
解决方案像其他人说的,ISO C ++不支持。但你可以解决它。只需使用std :: vector代替。
int * a = new int [N]
//填充
类C {
const std :: vector< int> v;
public:
C():v(a,a + N){}
};
I have the following class in C++:
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
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
?
This doesn't work:
a::a(void) :
b([2,3])
{
// other initialization stuff
}
Edit: 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.
解决方案 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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文