C++ typedef 类使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15501649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:26:40  来源:igfitidea点击:

C++ typedef class use

c++classtypedef

提问by kiriloff

Why use a typedef class {} Name?

为什么使用typedef class {} Name?

I learnt this in IBM C++ doc, no hint to use here.

我在IBM C++ doc中学到了这一点,这里没有提示。

回答by user93353

This is a hangover from the 'C' language.

这是'C'语言的后遗症。

In C, if you have

在 C 中,如果你有

struct Pt { int x; int y; };

then to declare a variable of this struct, you need to do

然后要声明这个结构的变量,你需要做

struct Pt p;

The typedef helped you avoid this in C

typedef 帮助您在 C 中避免这种情况

typedef struct { int x; int y; } Pt;

Now you can do

现在你可以做

Pt p;

in C.

在 C。

In C++, this was never necessary because

在 C++ 中,这从来没有必要,因为

class Pt { int x; int y; };

allowed you to do

允许你做

Pt p;

It provides no notational benefits in C++ as it does in C. OTOH, it leads to restrictions because this syntax does not provide any mechanism for construction, or destruction.

它在 C++ 中没有像在 C. OTOH 中那样提供符号上的好处,它会导致限制,因为这种语法不提供任何构造或销毁机制。

i.e. you cannot use the name typedef name in the constructor or destructor.

即您不能在构造函数或析构函数中使用名称 typedef 名称。

typedef class { int x; int y; } Pt;

You cannot have a constructor called Pt, nor a destructor. So in essence, most of the time, you shouldn't do this in C++.

你不能有一个叫做 Pt 的构造函数,也不能有一个析构函数。所以本质上,大多数时候,你不应该在 C++ 中这样做。

回答by Steve Jessop

This answer assumes that there's some interesting content in the class, not just {}.

这个答案假设课堂上有一些有趣的内容,而不仅仅是{}.

In C++, you can have a function with the same name as a class (for compatibility with C), but you pretty much never want to.

在 C++ 中,您可以拥有与类同名的函数(为了与 C 兼容),但您几乎永远不想这样做。

You can't have a function with the same name as a typedef, so doing this protects you against ill-disciplined name choices. Pretty much nobody bothers, and even if you're going to bother you'd probably write it:

您不能拥有与 typedef 同名的函数,因此这样做可以保护您免受不规范的名称选择。几乎没有人会打扰,即使您要打扰,您也可能会这样写:

class Name {};
typedef Name Name; // reserve the name

If the code you're referring to really is as written (I can't see it by following your link), then it's rather like class Name {};(which is a peculiar thing to write, why would you call an empty class Name?), but modified for the above consideration.

如果你所指的代码真的是这样写的(我无法通过你的链接看到它),那么它就像class Name {};(这是一个奇怪的东西,你为什么要调用一个空类Name?),但是修改了出于上述考虑。