如何在C++对象中初始化数组

Qua*_*002 7 c++ arrays initialization class

在阅读如何在C中初始化数组之后,特别是:

但是,不要忽视明显的解决方案:

int myArray [10] = {5,5,5,5,5,5,5,5,5,5};

我试过这样的事情:

#include <iostream>

class Something {
private:

int myArray[10];

public:

Something() {
    myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
}

int ShowThingy(int what) {
    return myArray[what];
}

~Something() {}
};

int main () {
   Something Thing;
    std::cerr << Thing.ShowThingy(3);
}
Run Code Online (Sandbox Code Playgroud)

我得到:

..\src\Something.cpp: In constructor 'Something::Something()':
..\src\Something.cpp:10:48: error: cannot convert '<brace-enclosed initializer list>' to 'int' in assignment
Run Code Online (Sandbox Code Playgroud)

在这种情况下显而易见的并不那么明显.我真的希望我的阵列的启动也更加动态.

我累了:

private:
    int * myArray;

public:
    Something() {
            myArray = new int [10];
            myArray = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
}
Run Code Online (Sandbox Code Playgroud)

这看起来很时髦,对编译器来说也是如此:

..\src\Something.cpp: In constructor 'Something::Something()':
..\src\Something.cpp:11:44: error: cannot convert '<brace-enclosed initializer list>' to 'int*' in assignment
Run Code Online (Sandbox Code Playgroud)

这也行不通:

private:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
Run Code Online (Sandbox Code Playgroud)

有:

 ..\src\Something.cpp:6:20: error: a brace-enclosed initializer is not allowed here before '{' token
 ..\src\Something.cpp:6:51: sorry, unimplemented: non-static data member initializers
 ..\src\Something.cpp:6:51: error: 'constexpr' needed for in-class initialization of static data member 'myArray' of non-integral type
Run Code Online (Sandbox Code Playgroud)

我一直做得非常好,学习什么不起作用,但不太好学习什么工作.

那么,我如何在类中使用数组的初始化列表{value,value,value}?

我一直试图弄清楚如何做一段时间并且非常困难,我有很多这样的列表我需要为我的应用程序制作.

Pra*_*ian 20

您需要在构造函数初始化列表中初始化该数组

#include <iostream>

class Something {
private:

int myArray[10];

public:

Something()
: myArray { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }
{
}

int ShowThingy(int what) {
    return myArray[what];
}

~Something() {}
};

int main () {
   Something Thing;
    std::cerr << Thing.ShowThingy(3);
}
Run Code Online (Sandbox Code Playgroud)

..\src\Something.cpp:6:51:抱歉,未实现:非静态数据成员初始值设定项

C++ 11还添加了对非静态成员变量的内联初始化的支持,但是正如上面的错误消息所述,您的编译器还没有实现它.

  • @derekerdmann [初始化列表](http://en.cppreference.com/w/cpp/utility/initializer_list)在C++ 11中添加 (2认同)