[英]Initialize an array inside Constructor in C++
I have defined an array within a class. 我在一个类中定义了一个数组。 I want to initialize the array with some values pre-decided value.
我想用一些预先确定的值来初始化数组。 If I could do it in definition only then it will be easier as I would have used
如果我只能在定义上做到这一点,那么它将比我以前使用的更容易
class A{
int array[7]={2,3,4,1,6,5,4};
}
But, I can't do that. 但是,我做不到。 This, I need to do inside Constructor.
这,我需要在构造函数内部进行。 But I can't use the same above syntax as it would create a new array inside Constructor and won't affect the array defined in class.
但是我不能使用上面相同的语法,因为它将在Constructor中创建一个新数组,并且不会影响在类中定义的数组。 What can be the easiest way to do it?
最简单的方法是什么?
class A{
public:
int array[7];
A::A(){
}
}
You can initialize the array in the constructor member initializer list 您可以在构造函数成员初始化器列表中初始化数组
A::A() : array{2,3,4,1,6,5,4} {
}
or for older syntax 或更旧的语法
A::A() : array({2,3,4,1,6,5,4}) {
}
Your sample should compile, using a compiler supporting the latest standard though. 您的示例应使用支持最新标准的编译器进行编译。
Also note your class declaration is missing a trailing semicolon 另请注意,您的类声明缺少尾随的分号
class A{
public:
int array[7];
A();
};
// ^
With C++11 you can write this: 使用C ++ 11可以编写以下代码:
class C
{
int x[4];
public:
C() : x{0,1,2,3}
{
// Ctor
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.