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

Why class data members can#39;t be initialized by direct initialization syntax?(为什么不能通过直接初始化语法来初始化类数据成员?)

本文介绍了为什么不能通过直接初始化语法来初始化类数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am curious to know that why class' data members can't be initialized using () syntax? Consider following example:

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

程序编译失败&给出以下错误.

The program fails in compilation & gives following errors.

11  9 [Error] expected identifier before numeric constant

11  9 [Error] expected ',' or '...' before numeric constant

为什么?是什么原因?C++ 标准对类数据成员的初始化有何规定?非常感谢您的帮助.谢谢

Why? What is the reason? What the C++ standard says about initialization of class data members? Your help is greatly appreciated. Thanks

推荐答案

引入该功能的早期提案解释说 这是为了避免解析问题.

这里只是其中的一个例子:

Here's just one of the examples presented therein:

不幸的是,这使得( expression-list )"形式的初始化器在解析声明时变得模棱两可:

Unfortunately, this makes initializers of the "( expression-list )" form ambiguous at the time that the declaration is being parsed:

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

struct T {
    int i(x); // member function declaration
    // ...
    typedef int x;
};

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

One possible solution is to rely on the existing rule that, if a declaration could be an object or a function, then it’s a function:

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

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

A similar solution would be to apply another existing rule, currently used only in templates, that if T could be a type or something else, then it’s something else; and we can use "typename" if we really mean a type:

struct S {
    int i(x); // unabmiguously a data member
    int j(typename y); // unabmiguously a member function
};

这两种解决方案都引入了许多用户可能会误解的微妙之处(comp.lang.c++ 上关于为什么int i();"在块范围内的许多问题证明了这一点没有声明默认初始化的 int).

Both of those solutions introduce subtleties that are likely to be misunderstood by many users (as evidenced by the many questions on comp.lang.c++ about why "int i();" at block scope doesn’t declare a default-initialized int).

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

The solution proposed in this paper is to allow only initializers of the "= initializer-clause" and "{ initializer-list }" forms. That solves the ambiguity problem in most cases. [..]

这篇关于为什么不能通过直接初始化语法来初始化类数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么不能通过直接初始化语法来初始化类数据成员?

基础教程推荐