为什么C++;是否为ctor/dtor使用类的名称? 有时候,我对C++的一个问题是定义构造函数的重复。在单独的cpp文件中定义系数时尤其如此。当我们泛指它们时,通常会说“构造函数”、“析构函数”、“复制构造函数”,或将它们缩写为“构造函数”、“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) { /* ... */ }

为什么C++;是否为ctor/dtor使用类的名称? 有时候,我对C++的一个问题是定义构造函数的重复。在单独的cpp文件中定义系数时尤其如此。当我们泛指它们时,通常会说“构造函数”、“析构函数”、“复制构造函数”,或将它们缩写为“构造函数”、“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) { /* ... */ },c++,syntax,dry,C++,Syntax,Dry,比以下内容更容易阅读: class SomeLongSelfDocumentingClassName { SomeLongSelfDocumentingClassName(int a, string b); SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other); ~SomeLongSelfDocumentingClassName(); }; SomeLongSel

比以下内容更容易阅读:

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选择了我没有想到的重复表达

< P>源于C++作为“C类”的演化。 < C和C++语言委员会(ISO)总是不愿意引入新的关键词,因为这样做可以破坏很多代码。code>ctor和
dtor
将是一个新的关键字。注意,由于C++支持函数重载,因此不需要额外添加代码< CCTRO/<代码>;即使最初的草案没有

此外,能够将一个成员函数命名为与类名称相同的名称将是一个混淆练习!因此,在这种情况下,将其保留用于建设和破坏是有意义的


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

因为标准上这么说是认真的吗?很明显,问题是什么原因导致将这样的事情纳入标准中。@KamilKoczurek当时给比亚恩写了一封电子邮件。已经很长时间了,但Brian大约20年前在牛津被问到了这个问题。@juanchopanza但通常像这样的问题只会导致对答案的猜测和猜测。我认为它们没有用。这是一个很好的理由。类名使自己成为一个保留字,但这些缩写将带走更多潜在的名称。尽管考虑到关于谁可以和不可以使用前导下划线的标准规则(指南?),2/3的额外关键字似乎无关紧要。介意编辑以便我可以撤销意外的否决票吗?@negaco:Done;-)使用
~
是非常明智的。这是一个奇妙的双关语。我记得读到过,Bjarne选择在析构函数前面加上否定运算符,因为析构函数的任务是否定构造函数的工作。我来看看是否能找到原始名称,类名不是保留字;这是一个标识符。