简体   繁体   English

如果在其他地方声明为const,为什么必须在定义时重复const说明符?

[英]Why does one have to repeat the const specifier at definition time, if declaration as const is done somewhere else?

After solving this simple issue , I had to ask : 解决了这个简单的问题之后 ,我不得不问:

-> In the H file in a class ex a const static member is defined, eg : ->在类ex的H文件中,定义了const静态成员,例如:

class ex {
    const static int my_ex;
};

-> In the CPP file the value is specified ->在CPP文件中指定值

ex::my_ex = 32;  

And then one gets the error "conflicting declarations" (as well as "does not name a type"). 然后出现错误“冲突声明”(以及“未命名类型”)。 I understand that the definition in the CPP file is also a declaration which does create a conflict seen from the linker BUT why only about the const specifier (and type) and not the static one ? 我知道CPP文件中的定义也是一个声明 ,它确实会产生从链接器BUT看到的冲突,为什么仅关于const说明符(和类型)而不是静态说明符? I only have to write 我只需要写

const int ex::my_ex = 32;

to get it to compile. 进行编译。 But not static ... Why not? 但是不是静态的...为什么不呢? Why can't I just define and not repeat declaration related steps (type, specific identifiers)? 为什么我不能只定义而不重复声明相关的步骤(类型,特定标识符)?

This is a historical thing. 这是历史性的事情。

Since C, static on a definition means "internal linkage". 从C开始,定义上的static表示“内部链接”。 When C++ came along, and classes were added to it, Bjarne needed a keyword to signify static members. 当C ++出现并添加了类时,Bjarne需要一个关键字来表示静态成员。 Not wanting to add new keywords (a preference that largely exists still to this day), he re-used static instead. 他不想添加新的关键字(直到今天仍然普遍存在这种偏好),他改为使用static关键字。

Now static meant two different things depending on where you put it. 现在, static表示两种不同的情况,具体取决于放置的位置。 So you can't write static here because it would mean something else. 因此,您不能在此处编写static ,因为它意味着其他含义。 Thus, the language doesn't require you to, as that would be silly. 因此,这种语言不需要您,因为那很愚蠢。

Beyond that reasoning, it just is . 除了这种推理, 事实就是这样 When you create a language, you balance simplicity of specification against simplicity of implementation against simplicity of use, and you come up with a set of rules that are the language. 当您创建一种语言时,您会在规范的简单性与实现的简易性与使用的简单性之间取得平衡,并提出了一系列规则。 At some point you have to stop quibbling over "why" some insignificant rule was created and just get on with writing your program. 在某些时候,您必须停止争论“为什么”创建了一些微不足道的规则,然后继续编写程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM