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

Mat*_*ers -2 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) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

比以下更容易阅读:

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) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

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

Bat*_*eba 5

它来自于C++的演变,即"C with classes".

C和C++语言委员会(目前的ISO)总是不愿意引入新的关键字,因为这样做会破坏很多代码.ctor并且dtor本来是一个新的关键词.请注意,cctor由于C++支持函数重载,因此不会另外需要; 即使最初的草案没有.

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

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