C ++ typedef类使用 [英] C++ typedef class use

查看:159
本文介绍了C ++ typedef类使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要使用 typedef class {} Name



我在 IBM C ++ doc ,这里没有提示使用。

解决方案

这是C语言的宿醉。



在C中,如果您有

  struct Pt {int x ; int y; }; 

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

  struct Pt p; 

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

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

现在你可以做

  Pt p; 


<$> 这是没有必要的,因为

  class Pt {int x; int y; }; 

允许您执行

  Pt p; 

它在C ++中不提供符号的好处,因为它在C. OTOH中,它导致了限制,因为语法不提供任何构造或销毁的机制。



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

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

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


Why use a typedef class {} Name ?

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

解决方案

This is a hangover from the 'C' language.

In C, if you have

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 struct { int x; int y; } Pt;

Now you can do

Pt p;

in C.

In C++, this was never necessary because

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.

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

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++.

这篇关于C ++ typedef类使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆