简体   繁体   English

C ++ typedef类使用

[英]C++ typedef class use

Why use a typedef class {} Name ? 为什么要使用typedef class {} Name

I learnt this in IBM C++ doc , no hint to use here. 我在IBM C ++ doc中学到了这一点,没有提示在这里使用。

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中提供,它会导致限制,因为这种语法不提供任何构造或破坏机制。

ie 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. 你不能拥有一个名为Pt的构造函数,也不能使用析构函数。 So in essence, most of the time, you shouldn't do this in C++. 所以从本质上讲,大多数情况下,你不应该在C ++中这样做。

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. 您不能拥有与typedef同名的函数,因此这样做可以保护您免受错误的名称选择。 Pretty much nobody bothers, and even if you're going to bother you'd probably write it: 几乎没有人会烦恼,即使你打算打扰你也可能会写下来:

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 {}; 如果你所指的代码真的是写的(我不能通过你的链接看到它),那么它就像class Name {}; (which is a peculiar thing to write, why would you call an empty class Name ?), but modified for the above consideration. (这是一个特殊的事情,为什么你会调用一个空类Name ?),但修改为上述考虑。

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

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