且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们不能在声明中初始化类成员?

更新时间:2022-11-23 17:12:46

非静态成员的初始化不能像C ++ 11之前一样。如果你用C ++ 11编译器编译,它应该很乐意接受你给的代码。

The initialization of non-static members could not be done like this prior to C++11. If you compile with a C++11 compiler, it should happily accept the code you have given.

我想,不允许它的第一个原因是因为数据成员声明不是一个定义。没有引入对象。如果您有一个数据成员如 int x; ,则不会创建 int 对象,直到您实际创建一个对象类的类型。因此,此成员上的初始化程序将会产生误导。只有在施工期间,才能为成员分配一个值,这正是成员初始化列表的作用。

I imagine that the reason for not allowing it in the first place is because a data member declaration is not a definition. There is no object being introduced. If you have a data member such as int x;, no int object is created until you actually create an object of the type of the class. Therefore, an initializer on this member would be misleading. It is only during construction that a value can be assigned to the member, which is precisely what member initialization lists are for.

还有一些技术问题需要解决可以添加非静态成员初始化。考虑下面的例子:

There were also some technical issues to iron out before non-static member initialization could be added. Consider the following examples:

struct S {
    int i(x);
    // ...
    static int x;
};

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

当解析这些结构时,在解析成员 i ,它是不明确是否是数据成员声明(如 S )或成员函数声明(如

When these structs are being parsed, at the time of parsing the member i, it is ambiguous whether it is a data member declaration (as in S) or a member function declaration (as in T).

添加功能后,这不是问题,因为您无法使用此parantheses语法初始化成员。您必须使用 brace-or-equal-initializer ,例如:

With the added functionality, this is not a problem because you cannot initialize a member with this parantheses syntax. You must use a brace-or-equal-initializer such as:

int i = x;
int i{x};

这些只能是数据成员,所以我们没有问题了。

These can only be data members and so we have no problem any more.

请参阅投标 N2628 更全面地考虑在提出非静态成员初始化器时必须考虑的问题。

See the proposal N2628 for a more thorough look at the issues that had to be considered when proposing non-static member initializers.