本文介绍了C风格/ C ++的正确性,struct / union / enum标记与类型名称是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的MyStruct(标记MyStruct)定义和MyStruct类型的类型定义似乎可以被gcc(至少4.6.2)和g ++完全编译。

The following definition of MyStruct (tag MyStruct) and type definition of type MyStruct seems perfectly compillable by gcc (at least 4.6.2) and by g++.

typedef struct MyStruct {
  int a;
  int b;
} MyStruct;

我的问题是:它是否容易出错(在C和/或C ++中)或样式不好使用标记名和类型名一样吗?

根据不是:

typedef struct tree_node tree_node;


但是我经常看到的代码风格如下:

But often I've seen code styled like:


  1. typedef struct tagMyStruct {...} MyStruct;

  2. typedef struct myStruct {。 ..} MyStruct;`

  3. typedef struct _MyStruct {...} MyStruct; <是的,我知道下划线+大写字母

  1. typedef struct tagMyStruct {...} MyStruct;
  2. typedef struct myStruct {...} MyStruct;`
  3. typedef struct _MyStruct {...} MyStruct; < yes, I know about underscore + capital letter

在每种情况下,有人都会在某种程度上使标签名称与不同名称。背后有任何实际的原因吗?

In each case someone went to some extent to make tag name differ from type name. Are there any practical reasons behind it?

侧面说明:我使用C ++编译器,但我希望这些定义与C兼容(我知道这对c ++来说是不好的风格)。为了维护某些调试工具的可用性,我需要所有标记名都有意义(例如,在未命名结构的情况下,不是自动生成的__unknown_something标记,例如,可以在Visual Studio类视图中查看)。

Side note: I use C++ compiler but I would like to be C compatible with those definitions (I know this is bad style for c++). For reasons of maintaining usability of some debug tools, I need all the tag names to be meaningful (not the automatically generated __unknown_something tags in case of unnamed structs you can, for example, see in visual studio class view).

同一个问题/问题也适用于联合和枚举。

Same issue/question apply to unions and enums.

推荐答案

从语言角度来讲,在C语言中完全可以和C ++,因为标记名存在于单独的命名空间(不是命名空间)中。

Language wise it is perfectly ok both in C and C++, as tag names exist in a separate name space (not namespace).

在C ++中,完全使用 typedef 绝对是不好的样式,因为它是多余的。无论您是否拥有 typedef MyStruct struct MyStruct

In C++ it is definitely bad style to use the typedef at all, as it is redundant. You can use both MyStruct and struct MyStruct whether you have the typedef or not.

如果您认为C兼容性比C ++风格更为重要,那是您的选择。 :-)

If you think C compatibility is more important than C++ style, that is your choice. :-)

这篇关于C风格/ C ++的正确性,struct / union / enum标记与类型名称是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:47