为什么C ++使用ctor / dtor类的名称?

时间:2017-11-15 15:48:12

标签: c++ syntax dry

偶尔让我对C ++感到烦恼的一件事是重复定义构造函数。在单独的cpp文件中定义ctors时尤其如此。当我们一般地引用它们时,我们通常会说“构造函数”,“析构函数”,“复制构造函数”,或者将它们缩写为“ctor”,“dtor”和“cctor”。甚至一些C ++编译器也会像这样缩写它们。那么为什么语言不能使用呢?不是

class SomeLongSelfDocumentingClassName
{
   ctor(int a, string b);
   cctor(const SomeLongSelfDocumentingClassName& other);
   ~dtor();
};

SomeLongSelfDocumentingClassName::ctor(int a, string b) { /* ... */ }
SomeLongSelfDocumentingClassName::cctor(const SomeLongSelfDocumentingClassName& other) { /* ... */ }
SomeLongSelfDocumentingClassName::dtor(int a, string b) { /* ... */ }

比阅读更容易阅读:

class SomeLongSelfDocumentingClassName
{
   SomeLongSelfDocumentingClassName(int a, string b);
   SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other);
   ~SomeLongSelfDocumentingClassName();
};

SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(int a, string b) { /* ... */ }
SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other) { /* ... */ }
SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(int a, string b) { /* ... */ }

不可否认,我一直在重复这种方式,以至于前一块看起来像胡说八道。有没有一个很好的理由Stroustrup选择了我没有想到的重复陈述?

1 个答案:

答案 0 :(得分:5)

它来自于C ++的演变,即“C with classes”。

C和C ++语言委员会(目前的ISO)总是不愿意引入新的关键字,因为这样做会破坏很多代码。 ctordtor将成为新的关键字。请注意,由于C ++支持函数重载,因此不需要cctor;即使最初的草稿没有。

此外,能够将成员函数命名为与类的名称相同将是混淆的练习!因此,在这种背景下保留建筑和破坏是有意义的。

使用类的名称作为析构函数~的构造函数当时是一个明智的选择。至少在我看来,它仍然是。