Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在不指定数组大小的情况下声明数组,但在C++;?_C++_Arrays_Language Lawyer_C++17 - Fatal编程技术网

C++ 如何在不指定数组大小的情况下声明数组,但在C++;?

C++ 如何在不指定数组大小的情况下声明数组,但在C++;?,c++,arrays,language-lawyer,c++17,C++,Arrays,Language Lawyer,C++17,如果数组具有初始值设定项,则允许在不明确说明其大小的情况下声明数组: // very fine: decltype(nums) is deduced to be int[3] int nums[] = { 5, 4, 3 }; 但是,在类中声明数组时,同样的方法不起作用: class dummy_class { // incomplete type is not allowed (VS 2019 c++17) int nums[] = { 5, 4, 3 }; }; 为什

如果数组具有初始值设定项,则允许在不明确说明其大小的情况下声明数组:

// very fine: decltype(nums) is deduced to be int[3]
int nums[] = { 5, 4, 3 }; 
但是,在类中声明数组时,同样的方法不起作用:

class dummy_class
{
    // incomplete type is not allowed (VS 2019 c++17)
    int nums[] = { 5, 4, 3 }; 
};

为什么会出现这种情况?

这是不允许的,因为非静态数据成员可能以不同的方式初始化(大小不同),包括。。。但数组的大小必须在编译时固定并已知,不能推迟到初始化时。e、 g

class dummy_class
{
    int nums[] = { 5, 4, 3 }; 
    dummy_class(...some_parameters) : nums { 5, 4, 3, 2 } ()
    dummy_class(...some_other_parameters) : nums { 5, 4, 3, 2, 1 } ()
};

由于这是不允许的,您可以执行以下两项操作之一:

  • 要么使用构造函数/方法进行初始化,要么使用向量类型声明
  • 或者尝试将变量设为静态,但我担心这对您的情况可能没有帮助

因为它完全不被C++语言规范所允许?也许可以使用
std::vector
来代替?因为ISO这么说。@我尝试过的某个程序员,但我的类型是不可复制的(我使用
int
作为示例),所以我根本不能使用初始值设定项列表构造。还可以聚合类本身的初始化:)