将数组传递给类的未声明大小的数组成员

Pass an array to an array member of undeclared size of a class

本文关键字:数组 未声明 组成员      更新时间:2023-10-16

我想要一个数组,它的值从main声明为类。这是示例代码。

class test{
public:
      const double arr[];
};
int main(){
     test t;
     t.arr[] = {1, 2};
    return 0;
}

当我尝试在main中初始化时,它会给我一个错误错误:意外表达式

但如果我在main中删除t.arr[],它编译得很好。

  1. const double arr[];-可变长度数组?在C++中无效
  2. t.arr[]-无效语法(没有参数的operator[]调用?),arr也是const,不能分配给任何数组

但你可以进行聚合初始化:

class test {
public:
    const double arr[2]; // fixed size
};
int main() {
    test t = {{1, 2}}; // not an assignment
    return 0;
}