4

I just saw a question where a non static member of a class was initialized in the class definition. But if I try to compile the following code I get an error from the compiler.

class MyClass
{
    int n = 2;
};

The error I'm getting is:

g++ -o ns nonstatic.cpp -Wall -Wextra -pedantic
nonstatic.cpp:3:13: error: ISO C++ forbids initialization of member ‘n’ [-fpermissive]
nonstatic.cpp:3:13: error: making ‘n’ static [-fpermissive]
nonstatic.cpp:3:13: error: ISO C++ forbids in-class initialization of non-const static member ‘n’

I always thought I must initialize such member in the constructor like this:

class MyClass
{
    public:
        MyClass ( void ) : n(2) {}
    private:
        int n;
};

Or with n initialized inside of the body of the constructor. So my question is: when is one allowed to initialize a non static member outside the context of a class constructor?

kind regards,

4

1 回答 1

8

何时允许在 C++ 中初始化类的非静态成员?

在 C++11 中已经可以做到这一点。

只需传入-std=c++11命令行即可。

于 2013-06-27T19:11:04.043 回答