-1

I want to have an array whose values be declared from main to a class. Here's the sample code.

class test{
public:
      const double arr[];
};

int main(){

     test t;
     t.arr[] = {1, 2};
    return 0;
}

When I try to intialize in the main it gives me an error error:unexpected expression.

But if I remove the t.arr[] in main, it compiles fine.

user42826
  • 101
  • 1
  • 8

1 Answers1

0
  1. const double arr[]; - variable length array? Invalid in C++.
  2. t.arr[] - invalid syntax (operator[] call with no arguments?), arr is also const and you can't assign to any arrays.

But you can do aggregate intialization:

class test {
public:
    const double arr[2]; // fixed size
};

int main() {

    test t = {{1, 2}}; // not an assignment
    return 0;
}
Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • Just realized, perhaps I should have given it as (t.arr)[], which sounds more reasonable. I didn't understand why it compiles first off, if a variable binned array is given. – user42826 Apr 28 '16 at 21:21