简体   繁体   中英

Why I can't 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'm getting an error on the float mat[3] = {0.0, 0.0, 0.0}; . It says Error C2059: syntax error : '{' and error C2334: unexpected token(s) preceding '{'; skipping apparent function body.

I am create the array correctly aint I? What is the problem then?

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

class Matrix{
public:
    Matrix() : mat({0.0, 0.0, 0.0}) {};
    ~Matrix();

protected:
    float mat[3];
};

The above defines the constructor inline; if you define the constructor separately, move the initialization list (ie the code between the colon : and the opening brace { ) together with the constructor definition.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM