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

标签 c++ arrays class initialization

看完How to initialize an array in C ,特别是:

Don't overlook the obvious solution, though:

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);
}

然后我得到:

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

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

我累了:

private:
    int * myArray;

public:
    Something() {
            myArray = new int [10];
            myArray = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
}

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

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

这也不起作用:

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

与:

 ..\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

我一直做得很好,学习了哪些是行不通的,但学习哪些是行之有效的却不是很好。

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

一段时间以来,我一直在努力弄清楚如何做到这一点,但我非常困惑,我需要为我的应用制作许多此类列表。

最佳答案

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

#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);
}

..\src\Something.cpp:6:51: sorry, unimplemented: non-static data member initializers

C++11 还添加了对非静态成员变量的内联初始化的支持,但如上述错误消息所述,您的编译器尚未实现此功能。

关于c++ - 如何在 C++ 对象中初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10694689/

相关文章:

java - 向按频率排序的数组中插入一个元素,然后再次按频率对数组进行排序

c++ - 重新实现鼠标事件时对 QGraphicsView 的奇怪影响

c++ - opencv 解码格雷码模式相机校准错误。如何格式化内在和外在结果?

python - 在 numpy 数组中找到最大上三角项的索引的有效方法?

arrays - 用jq从数组中删除空白字符串?

java - 无状态对象的良好实践与否

c++ - 生成 C++ 项目中所有类的列表

c++ - 如何使用不同的方法实现从抽象派生的类?

C++:复制数组

C++ 多次掷骰子