c++ - 是否允许在类构造函数之外初始化非静态成员?

标签 c++ initialization

我刚刚看到一个问题,在类定义中初始化了一个类的非静态成员。但是如果我尝试编译以下代码,我会从编译器中得到一个错误。

class MyClass
{
    int n = 2;
};

我得到的错误是:

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’

我一直认为我必须像这样在构造函数中初始化这样的成员:

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

或者用 n 在构造函数体内初始化。 所以我的问题是:什么时候允许在类构造函数的上下文之外初始化非静态成员?

亲切的问候,

最佳答案

when is one allowed to initialize a non static member of a class in C++?

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

只需将 -std=c++11 传递到命令行即可。

关于c++ - 是否允许在类构造函数之外初始化非静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17351329/

相关文章:

c++ - 命名空间中的函数模板特化

c - 如何在C编程中初始化多维数组

c++ - 如何使用 Xenroll 和 CertEnroll 创建在所有版本的窗口上运行的 "Certificate Signing Request"?

c++ - 在通过 native 字符串创建 BSTR(使用 _bstr_t 包装器)时,如何设置长度?

c++ - GLFW - 与 Visual Studio 2012 链接的问题

c++ - 使用 { } 的 Visual Studio 2012 C++ 数组初始化

c++ - 初始化空的2D vector ?

c++ - 抽象类 C++ 的 VTABLE

c++ - 从类实例 vector 中提取类成员(作为新 vector )

C++ 全局变量和初始化顺序