简体   繁体   English

关于C vrs C ++中的结构变量声明

[英]Regarding struct variable declaration in C vrs C++

in C 在C

   struct node {
          int x;
   };

   node *y; // incorrect
   struct node *y; // correct  

in C++ 在C ++中

   struct node{
         int x;
   };

   node *y; // correct
   y = new node; // correct

Question: Why is the tag name acceptable to create a pointer in C++ not in C? 问题:为什么在C ++中不能在C中创建指针,但可接受标签名称?

Because the C++ standard says so, and the C standard doesn't. 因为C ++标准如此,而C标准却没有。

I would say that C++ made the change to make classes easier to use (remember, classes and structs are fundamentally the same thing in C++; they only differ in default visibility), and C didn't follow suit because that would break tons of existing C code. 我要说的是C ++进行了更改,使类更易于使用(请记住,类和结构在C ++中本质上是同一件事;它们在默认可见性上是不同的),而C并没有效仿,因为这会破坏大量现有的C代码。

The reason is not just because the standard says so, C++ actually has namespaces while the struct keyword allowed for a primitive form of namespace in C which allowed you to have a struct and a non-struct identifier with the same name. 原因不只是因为该标准这样说,C ++实际上具有名称空间,struct关键字允许C语言中的名称空间为原始形式,它允许您具有相同名称的struct和non-struct标识符。 We can see this primitive form of a namespace from the C99 draft standard section 6.2.3 Name spaces of identifiers which says: 我们可以从C99草案标准第6.2.3“标识符的命名空间”中看到这种命名空间的原始形式,其中表示:

If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. 如果在翻译单元的任何位置都可以看到一个以上的特定标识符声明,则语法上下文会消除指向不同实体的用法的歧义。 Thus, there are separate name spaces for various categories of identifiers, as follows: 因此,对于各种类别的标识符,存在单独的名称空间,如下所示:

and has the following bullets: 并具有以下项目符号:

— label names (disambiguated by the syntax of the label declaration and use); —标签名称(由标签声明和使用的语法消除);

— the tags of structures, unions, and enumerations (disambiguated by following any24) of the keywords struct, union, or enum); —关键字struct,union或enum的结构,联合和枚举的标签(通过遵循any24消除歧义);

— the members of structures or unions; —机构或工会的成员; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator); 每个结构或联合为其成员都有一个单独的名称空间(通过用于通过。或->运算符访问成员的表达式的类型来消除歧义);

— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants). —所有其他标识符,称为普通标识符(在普通声明符中声明或作为枚举常量声明)。

I could make up an example but POSIX gives us a great example with stat which is both a function and a struct : 我可以组成一个示例,但是POSIX通过stat给出了一个很好的示例,它既是函数又是结构

int stat(const char *restrict path, struct stat *restrict buf);
    ^^^^                            ^^^^^^^^^^^

If you want to write the way node* y in C, just 如果要在C中编写node * y的方式,只需

typedef struct node {
    int x;
} node;

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

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