是“私人”的; C 关键字?
ANSI C(或与此相关的任何其他 C)中是否有“私有”或“公共”关键字,或者它们仅在 C++(以及 Java、C# 等)中添加?
Are 'private' or 'public' keywords in ANSI C (or any other C for that matter), or were they only added in C++ (and Java, C#, ...)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
private
不是 C89 或 C99 关键字。 请参阅维基教科书上的 C 编程/参考表*。此外,C 与 Java 和 C# 没有任何关系(实际上,C++ 也没有关系)。 然而,反之则不然——例如,C++ 是从 C 发展而来的。
* 需要更好的参考!
** 实际上,C89“借用”了< C++ 中的 code>const 和
volatile
关键字。 同样,C99“借用”了inline
关键字,还添加了_Bool
和_Complex
(就像C++的bool
和<分别为代码>复杂)[需要引用]。private
is not a C89 or C99 keyword. See C Programming/Reference Tables on Wikibooks*.Also, C has nothing** to do with Java and C# (and, really, not C++ either). However, the converse is not true -- C++ grew from C, for example.
* Better reference needed!
** Actually, C89 "borrowed" the
const
andvolatile
keywords from C++. Likewise, C99 "borrowed" theinline
keyword, and also added_Bool
and_Complex
(like C++'sbool
andcomplex
, respectively) [citation-needed].两者都不是 C 关键字,但有些人会执行以下操作:
更新:
对于那些认为执行上述操作是坏主意的人,我会同意。 但它确实解释了为什么有人可能认为
public
或private
是 C 关键字。对于那些认为它无法在 C 中编译的人,请尝试以下操作:
对于那些认为它无法在 C++ 中编译的人,是的,上面的程序可以。
更新:
实际上,由于 C++ 标准的这一部分,这是未定义的行为:
因此,上面和下面的示例不需要在 C++ 中做任何正常的事情,这是一件好事。 我的答案对于 C 来说仍然完全有效(直到它被证明是错误的!:-))。
对于具有私有成员的 C++ 类,您可以执行类似的操作(被视为滥用),如下所示:
main.c:
message.hpp:
Neither are C keywords, but some people do the following:
Update:
For those who think it is a bad idea to do the above, I would agree. But it does explain why someone might think
public
orprivate
are C keywords.For those who think it won't compile in C, try this:
For those who think it won't compile in C++, yes the above program will.
Update:
Well actually it is undefined behaviour due to this part of the C++ standard:
So the example above and below are not required to do anything sane in C++, which is a good thing. My answer still is completely valid for C (until it is proven to be wrong! :-) ).
In the case of a C++ class with private members, you can do something similar (considered an abuse) like this:
main.c:
message.hpp:
static 与 private 不同,因为即使在类的构造函数中也无法读取静态变量 em>(C 语言中初始化结构体成员的函数)。
您只能在定义静态变量的代码部分(在函数、结构体中……)中使用静态变量。
static isn't like private, given that you can't read a static variable even in the constructor of the class (the function which inits members of a struct in C language).
You only can use static variables in the part of the code where they were defined (in a function, a struct, ...).