且构网

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

为什么在记录中不允许无参数构造函数?

更新时间:2023-11-14 23:30:28

I不能给出明确的答案(只有编译器生成器可以),但是我怀疑它与Delphi的.NET无关,而与Delphi与C ++ Builder的关系无关。

I can't give you a definitive answer (only the compiler builders can), but I suspect it is not related to Delphi's .NET past, but rather to Delphi's relation with C++Builder.

作为 cppreference 说:


默认构造函数是可以不带参数调用的构造函数(可以使用空参数列表或默认参数定义)

A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter).

C ++允许无参数构造函数,这些无参数构造函数将成为C ++中的默认构造函数。在许多情况下都会调用默认构造函数,例如如果您只是声明:

C++ allows for parameterless constructors, and these parameterless constructors would become the default constructor, in C++. A default constructor is called in many situations, e.g. if you simply declare:

Foo myFoo;

调用默认构造函数。在Delphi中不会发生这种情况,但是C ++程序员可能会期望这样。同样,如果您这样做:

The default constructor is called. This does not happen in Delp but a C++ programmer might expect it. Similarly, if you do:

Foo elements[1000];

在每个元素上调用默认构造函数(我检查过)。在Delphi中也不会发生这种情况,尽管C ++程序员可能会想到。

The default constructor is called on each element (I checked that). This also doesn't happen in Delp although a C++ programmer might expect it.

其他暗示这与C ++相关:

Other hints that this is C++-related:


  • 具有不同名称的构造函数(例如 Init )也不允许。这似乎表明与C ++或C#冲突,因为在这两种构造函数中,构造函数都具有类或结构的名称,因此任何无参数的构造函数都将映射到 Foo() (在名为 Foo 的结构或类中。)

  • 仅具有默认参数的构造函数也不允许。这与仅具有默认参数的默认构造函数的cppreference描述相匹配。

  • Constructors with different names (e.g. Init) are not allowed either. This seems to point to conflicts with C++ or with C#, as in both, constructors have the name of the class or struct, so any parameterless constructor would be mapped to Foo() (in a struct or class called Foo.)
  • Constructors with only default parameters are not allowed either. This matches the cppreference description for default constructors with only default arguments.

总而言之,有一些提示表明无参数构造函数(或带有无参数构造函数的仅默认参数)与C ++(即C ++ Builder)冲突,这就是为什么不允许使用它们的原因。

All in all, there are hints that parameterless constructors (or ones with only default parameters) conflict with C++ (i.e. C++Builder) and that that is why they are not allowed.

请注意,这并不是与C ++的差异所引起的唯一限制:在Delphi中,您也不能在浮点类型之间进行整数转换,因为在C和C ++中,这将导致转换,而在Delphi中,它将仅导致对位的重新解释。为了不使从C或C ++进入Delphi的人们感到困惑,将转换限制放在浮点类型上。可能还有更多。