能否给我讲解一下typedef和typedef typename的区别,以及什么时候应该使用哪一个?

AeoLusFeng 2002-03-27 09:38:38
看了很多书籍,讲解都不是很清楚,所以希望各位高手能够赐教!谢谢
...全文
1362 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
lizmei001 2002-03-28
  • 打赏
  • 举报
回复
帮你UP
cococut 2002-03-28
  • 打赏
  • 举报
回复

typedef 最复杂的用法就是定义函数指针,举下面的例子:

#include <iostream.h>
#include <stdlib.h>

extern void func1(); // Declare 4 functions.
extern void func2(); // 在别的地方定义
extern void func3();
extern void func4();

typedef void (*pvfn)(); // function that takes no arguments
// and returns type void.

void main( int argc, char * argv[] )
{
// Declare an array of pointers to functions.
pvfn pvfn1[] = { func1, func2, func3, func4 };

// Invoke the function specified on the command line.
if( argc > 0 && *argv[1] > '0' && *argv[1] <= '4' )
(*pvfn1[atoi( argv[1] ) - 1])();
}

AeoLusFeng 2002-03-28
  • 打赏
  • 举报
回复
恩,看来我是给说了很多人的疑问,呵呵,表扬一下自己
不过分还是照给!感谢赐教!!!
mis98ZB 2002-03-28
  • 打赏
  • 举报
回复
哈哈,学到了!
hcpp 2002-03-27
  • 打赏
  • 举报
回复
受教了!!!
cococut 2002-03-27
  • 打赏
  • 举报
回复
typedef:是用于定义类型用的
1,为了简化,清晰。比如,
vector<list<int *>*> temp(10);
可以简化为
typedef list<int *> listnum;
typedef vector<listnum *> vectornum;
vectornum temp(10);
2,定义指向成员的指针。
class A{
virtual sup() = 0;
}
typedef void (A::* pt)();
void f(A *a)
{
pt ptemp = &A::sup;
}
typename:
template的含义有两个:
1)typename var_name;表示var_name的定义还没有给出,这个语句通常出现在模版的定义内,例如:
template <class T>
void f() {
typedef typename T::A TA; // 声明 TA 的类型为 T::A
TA a5; // 声明 a5 的类型为 TA
typename T::A a6; // 声明 a6 的类型为 T::A
TA * pta6; // 声明 pta6 的类型为 TA 的指针
}

因为T是一个模版实例化时才知道的类型,所以编译器更对T::A不知所云,为了通知
编译器T::A是一个合法的类型,使用typename语句可以避免编译器报错。
2)template < typename var_name > class class_name; 表示var_name是一个类型,
在模版实例化时可以替换任意类型,不仅包括内置类型(int等),也包括自定义类型class。
这就是问题中的形式,换句话说,在template<typename Y>和template<class Y>中,
typename和class的意义完全一样。
marconi 2002-03-27
  • 打赏
  • 举报
回复
to cococut(往事如屁!!!):能否将typedef的使用详细讲一讲。我还不太明白比如定义函数指针,指针数组之类的typedef用法。
zfbt 2002-03-27
  • 打赏
  • 举报
回复
噢!我也知道了!
fixopen 2002-03-27
  • 打赏
  • 举报
回复
typedef orgtype newtype
当orgtype编译器不知道是一种类型时,用:
typedef typename orgtype newtype
最常见的用法是,在类里面typedef了一个newtype,在另一个地方使用时。
prototype 2002-03-27
  • 打赏
  • 举报
回复
cococut is all right.

just show some more examples:

class A; // let compiler know A is a class here. i may define it later.

typedef A A_type; // ok
typedef A::B AB_type; // error. the compiler doesn't 'B' is a type or something else.

typedef typename A::B AB_type; // ok. you tell the compiler B is really a type, so it will not complain.

class A {
public:
typedef int B; // i kept my promise to really define 'B' as type here.
...
};

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧