C++ 错误:从初始值设定项列表分配给数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15603158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: Assigning to an array from an initializer list
提问by Kearito
I have a class such as:
我有一个类,例如:
class dialog
{
public:
double dReturnType[][5][3];
};
#include <cstdlib>
#include <iostream>
include <string>
using namespace std;
#include "dialog.h";
int main(int argc, char *argv[])
{
dialog People;
People.dReturnType[0][1] = {1.2,2.3,6.6};
return 0;
}
It returns:
它返回:
[Warning] extended initializer lists only available with -std=c++11 or -std=gnu11 [enabled by default] [Error]: assigning to an array from an initializer list
[警告] 扩展初始化列表仅适用于 -std=c++11 或 -std=gnu11 [默认启用] [错误]:从初始化列表分配给数组
I've looked it up online a bit and really couldn't find a way to get around this. I'd prefer not editing the class within it's on class file (kinda defeats the purpose). Any help?
我在网上查了一下,真的找不到解决这个问题的方法。我不想在类文件中编辑类(有点违背目的)。有什么帮助吗?
Note: the class is in a separate project file
注意:该类在一个单独的项目文件中
回答by masoud
Initializer lists are just usable during initialization.
初始化列表仅在初始化期间可用。
If you want use std::initializer_list
after initialization:
如果要std::initializer_list
在初始化后使用:
auto init = std::initializer_list<double>({1.2,2.3,6.6});
std::copy(init.begin(), init.end(), your_array);
回答by Breno Santos
You can't initialize a extended list unless you're on c++11.
除非使用 c++11,否则无法初始化扩展列表。
And If I was you a good habit is to use * instead of empty "[]" and allocate memory when you know the size (with new or malloc). dReturn type on your program is a pointer of matices.
如果我是你,一个好习惯是使用 * 而不是空的“[]”,并在知道大小时分配内存(使用 new 或 malloc)。dReturn 类型在你的程序是一个 matices 的指针。
And you're giving a full list to only one member of the vector.
并且您仅向向量中的一个成员提供了完整列表。
People.dReturnType[0]={1.2,2.3,6.6};
That makes more sense.
这更有意义。
Try to encapsulate and use/create initializer functions that will help you to do that too. C++ will put all 0 at start, but you can do a function and call:
尝试封装和使用/创建初始化函数,这也将帮助您做到这一点。C++ 会在开始时把所有的 0,但你可以做一个函数并调用:
dialog People("the_atributes_are_here").
It's a good pratice to make the dReturnType private and use functions to acess it data and insert/modify things. But that is up to you.
将 dReturnType 设为私有并使用函数来访问它的数据和插入/修改内容是一种很好的做法。但这取决于你。