使用构造函数的类内成员初始化程序:是否允许?

时间:2015-06-05 16:23:05

标签: c++ c++11 constructor initialization in-class-initialization

我最近在Danny Kalev的文章Get to Know the New C++11 Initialization Forms中找到了一段有趣的代码:

class C
{
string s("abc");
double d=0;
char * p {nullptr};
int y[5] {1,2,3,4};
public:
C();
};

string s("abc");行对我来说似乎很可疑。我认为在成员在类中初始化时不允许使用构造函数。 这段代码(简化为class C { string s("abc");};`)不用

编译
  • clang 3.6.1(编译器参数为-std=c++11 -Wall -Wextra -Werror -pedantic-errors
  • g++ 5.1.0(编译器参数相同:-std=c++11 -Wall -Wextra -Werror -pedantic-errors
  • vc++ 18.00.21005.1(编译器参数为/EHsc /Wall /wd4514 /wd4710 /wd4820 /WX /Za
  • vc++ 19.00.22929.0(编译器参数由服务预定义:/EHsc /nologo /W4 /c

我是对的,这篇文章中有错误吗?

2 个答案:

答案 0 :(得分:4)

  

我是对的,这篇文章中有错误吗?

是的,这篇文章中的错误。

在数据成员的声明中只允许大括号或等于初始化dpy的初始化是正确的,但不是s。这样做的理由是,使用表达式列表会使用函数声明模糊声明,并且还会导致与类体中的名称查找冲突。

答案 1 :(得分:1)

An example from Bjarne Stroustrup:

class A {
    public:
        A() {}
        A(int a_val) : a(a_val) {}
        A(D d) : b(g(d)) {}
        int a = 7;
        int b = 5;  
    private:
        HashingFunction hash_algorithm{"MD5"};  // Cryptographic hash to be applied to all A instances
        std::string s{"Constructor run"};       // String indicating state in object lifecycle
    };