为什么不能通过直接初始化语法初始化类数据成员?

Des*_*tor 6 c++ initialization language-lawyer

我很想知道为什么类'数据成员不能使用()语法初始化?考虑以下示例:

#include <iostream>
class test
{
    public:
        void fun()
        {
            int a(3);
            std::cout<<a<<'\n';
        }
    private:
        int s(3);    // Compiler error why???
};
int main()
{
    test t;
    t.fun();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序编译失败并出现以下错误.

11  9 [Error] expected identifier before numeric constant

11  9 [Error] expected ',' or '...' before numeric constant
Run Code Online (Sandbox Code Playgroud)

为什么?是什么原因?关于类数据成员初始化的C++标准是什么意思?非常感谢您的帮助.谢谢

Lig*_*ica 11

导致该功能介绍的早期提议解释了这是为了避免解析问题.

这里只是其中一个例子:

不幸的是,这使得" ( 表达式列表 ) "的初始化程序在解析声明时不明确:

struct S {
    int i(x); // data member with initializer
    // ...
    static int x;
};

struct T {
    int i(x); // member function declaration
    // ...
    typedef int x;
};
Run Code Online (Sandbox Code Playgroud)

一种可能的解决方案是依赖现有规则,如果声明可以是对象或函数,那么它是一个函数:

struct S {
    int i(j); // ill-formed...parsed as a member function,
              // type j looked up but not found
    // ...
    static int j;
};
Run Code Online (Sandbox Code Playgroud)

一个类似的解决方案是应用另一个现有的规则,目前只在模板中使用,如果T可能是一个类型或其他东西,那么它是其他的东西; 我们可以使用" typename"如果我们真的是一个类型:

struct S {
    int i(x); // unabmiguously a data member
    int j(typename y); // unabmiguously a member function
};
Run Code Online (Sandbox Code Playgroud)

这两种解决方案都引入了很多可能被许多用户误解的细微差别(comp.lang.c ++上的许多问题都证明了int i();"块大小的原因" 并未声明默认初始化int).

本文提出的解决方案是仅允许" = initializer-clause "和" { initializer-list } "形式的初始化器.这解决了大多数情况下的歧义问题.[..]