Warning: non-static data member initializers only

2020-04-14 09:09发布

I have this code

class Move
{
    public:
        Move()
        {
            name = "";
            type_num = 18;
            power = 0;
            accuracy = 0;
            type = "???";
        }

        Move(string a, int b, int c, int d)
        {
            name = a;
            type_num = b;
            power = c;
            accuracy = d;
            /*lines of code to give type a string variable depending on the value of type_num*/
        }

    private:
        string name, type;
        int type_num, power, accuracy;
};

class Moveset
{
    public:
        Moveset()
        {
        }               
    private:
        Move slot1{"MOVE 1", rand() % 18, 10*(rand() % 15 + 1), 5 * (rand() % 11 + 10)};
};

And the compiler gave me this Warning for declaring the object slot1 under the private section in class Moveset.

464 83  C:\Users\N\Desktop\C++\Poke\Poke.cpp    [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
464 15  C:\Users\N\Desktop\C++\Poke\Poke.cpp    [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
464 83  C:\Users\N\Desktop\C++\Poke\Poke.cpp    [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11

Although it gave me the warning but apparently it didnt affect the programme running. Does it actually affect anything? and what am I doing wrong here?

Edit: And what is the diifference between a static member initializer and non-static member initializer?

2条回答
一夜七次
2楼-- · 2020-04-14 09:54

You asked:

Edit: And what is the difference between a static member initializer and non-static member initializer?

Not much different.
The intializer to initialize a static member is a static member initializer.
The intializer to initialize a non-static member is a non-static member initializer.

class foo
{    
    static int var2 = 20;  // static member initializer
    int var1 = 10;         // non-static member initializer
};
查看更多
对你真心纯属浪费
3楼-- · 2020-04-14 09:59

The compiler probably allows it as an extension, it's really not allowed in the older C++ standards.

Either initialize the object through a constructor initializer list, or enable C++11 using the flags the compiler tells you.


Example using a constructor initialize list:

class Moveset
{
public:
    Moveset()
        : slot1{"MOVE 1", rand() % 18, 10*(rand() % 15 + 1), 5 * (rand() % 11 + 10)}
    {
    }
private:
    Move slot1;
};

You seem to be using an IDE of some kind, so I don't know how to add the flags, but usually somewhere in the project settings there is a tab for the compiler and its settings, where you should be able to add flags (if there isn't a checkbox for C++11 already), just add -std=c++11 there.

查看更多
登录 后发表回答