Why can't I create my array (C ++)?

I have the following code:

#pragma once class Matrix{ public: Matrix(); ~Matrix(); protected: float mat[3] = {0.0, 0.0, 0.0}; }; 

but I get an error message float mat[3] = {0.0, 0.0, 0.0}; . It speaks of error C2059: syntax error: '{' and error C2334: unexpected token (s) preceding '{'; skipping the visible function body.

I am creating the array correctly, and I? What is the problem?

+6
source share
2 answers

C ++ 03 does not support inline initialization of member fields. You need to transfer this initialization to the constructor, for example ( link to the demo ):

 class Matrix{ public: Matrix() : mat({0.0, 0.0, 0.0}) {}; ~Matrix(); protected: float mat[3]; }; 

The above defines an inline constructor; if you define the constructor separately, move the initialization list (that is, the code between the colon : and the opening bracket { ) along with the constructor definition.

+11
source

C ++ did not support non-static data element initializers until the C ++ 11 standard was ratified. To use this feature, you must have a compiler that supports C ++ 11. In addition, it is often disabled by default, so you probably need to enable it manually. For GCC, specify std=c++11 . For Clang do -std=c++11 -stdlib=libc++ . If you are using anything else, check the documentation.

+7
source

All Articles