c/c++ typedef

本文详细解释了C++中的typedef关键字,包括其用途、使用方法、类型定义的规则及属性,以及如何定义函数和应用类型别名。通过示例展示了如何在C++程序中使用typedef来简化代码。
 
Home	

C++ Keywords: typedef
 

An Alias for a Known Type

In C++, you can declare a variable using one of the built-indata types:

#include <iostream>

using namespace std;



int main()

{

	int number = 248;

	return 0;

}

In the same way, you can declare an array or a pointer. Youcan also declare various variables on the same line. Here are examples:

#include <iostream>

#include <string>

using namespace std;



int main()

{

	int number = 248;

	double *distance = new double(390.82);

	string countries[] = { "Ghana", "Angola", "Togo",

	                       "Tunisia", "Cote d'Ivoire" };



	cout << "Number: " << number << endl;

	cout << "Distance: " << *distance << endl;

	cout << "Countries:\n";

	for(int i = 0; i < sizeof(countries) / sizeof(string); i++)

		cout << '\t' << countries[i] << endl;



	cout << endl;

	return 0;

}

If you plan to use the same type of data for manydeclarations, you can customize its name. In C++, thetypedef keywordallows you to create an alias for a data type. The formula to follow is:

typedef [attributes] DataType AliasName;

The typedef keyword is required. The attributeis not.

The typedef keyword can be followed by any C++ built-in datatype, includingint, short, signed, unsigned,char,signed char, unsigned char,double, long, or longdouble. The data type can also be an existing class that either is providedby one of the libraries that ship with the C++ compiler. For example, it can bethestring class. The data type can also be a pointer to a known type.

On the right side of the data type, type the name that willbe used to represent the data type or the pointer. Here are examples:

#include <iostream>

#include <string>

using namespace std;



typedef short SmallNumber;

typedef unsigned int Positive;

typedef double* PDouble;

typedef string FiveStrings[5];



int main()

{



	cout << endl;

	return 0;

}

    In typedef short SmallNumber, SmallNumber can now be used as a data type to declare a variable for a small integer.
    In the second example, typedef unsigned int Positive, The Positive word can then be used to declare a variable of anunsigned int type.
    After typedef double* PDouble, the word PDouble can be used to declare a pointer to double.
    By defining typedef string FiveStrings[5], FiveStrings can be used to declare an array of 5 strings with each string being of typestring.

Based on this rule, you can declare the variables based on types you have typed defined. Here are examples:

#include <iostream>

#include <string>

using namespace std;



typedef short SmallNumber;

typedef unsigned int Positive;

typedef double* PDouble;

typedef string FiveStrings[5];



int main()

{

	SmallNumber temperature = -248;

	Positive height = 1048;

	PDouble distance = new double(390.82);

	FiveStrings countries = { "Ghana", "Angola", "Togo",

		                  "Tunisia", "Cote d'Ivoire" };



	cout << "Temperature: " << temperature << endl;

	cout << "Height:      " << height << endl;

	cout << "Distance:    " << *distance << endl;

	cout << "Countries:\n";

	for(int i = 0; i < sizeof(countries) / sizeof(string); i++)

		cout << '\t' << countries[i] << endl;



	cout << endl;

	return 0;

}

This would produce:

Temperature: -248

Height:      1048

Distance:    390.82

Countries:

        Ghana

        Angola

        Togo

        Tunisia

        Cote d'Ivoire

Type-Defining a Function

The typedef keyword can also be used to define an alias for a function. In this case, you must specify the return type of the function and its type(s) of argument(s), if any. Another rule is that the definition must specify that it is a function pointer. Here is an example:

#include <iostream>

#include <string>

using namespace std;



typedef short SmallNumber;

typedef unsigned int Positive;

typedef double* PDouble;

typedef string FiveStrings[5];

typedef double (*Addition)(double value1, double value2);



double Add(double x, double y)

{

	double result = x + y;

	return result;

}



int main()

{

	SmallNumber temperature = -248;

	Positive height = 1048;

	PDouble distance = new double(390.82);

	FiveStrings countries = { "Ghana", "Angola", "Togo",

		                      "Tunisia", "Cote d'Ivoire" };

	Addition plus;



	cout << "Temperature: " << temperature << endl;

	cout << "Height:      " << height << endl;

	cout << "Distance:    " << *distance << endl;

	cout << "Countries:\n";

	for(int i = 0; i < sizeof(countries) / sizeof(string); i++)

		cout << '\t' << countries[i] << endl;



	plus = Add;

	cout << "3855.06 + 74.88 = " << plus(3855.06, 74.88) << endl;

	return 0;

}

This would produce:

Temperature: -248

Height:      1048

Distance:    390.82

Countries:

        Ghana

        Angola

        Togo

        Tunisia

        Cote d'Ivoire

3855.06 + 74.88 = 3929.94

The Attribute of a Type-Definition

The typedef keyword can be followed by an attribute before the data type. In its simplest form, the attribute can be that of an access level such aspublic, private, or protected. Here are examples:

#include <iostream>

#include <string>

using namespace std;



typedef public short SmallNumber;

typedef private unsigned int Positive;

typedef protected double* PDouble;

typedef public string FiveStrings[5];

typedef private double (*Addition)(double value1, double value2);



double Add(double x, double y)

{

	double result = x + y;

	return result;

}



int main()

{

	SmallNumber temperature = -248;

	Positive height = 1048;

	PDouble distance = new double(390.82);

	FiveStrings countries = { "Ghana", "Angola", "Togo",

		                  "Tunisia", "Cote d'Ivoire" };

	Addition plus;



	cout << "Temperature: " << temperature << endl;

	cout << "Height:      " << height << endl;

	cout << "Distance:    " << *distance << endl;

	cout << "Countries:\n";

	for(int i = 0; i < sizeof(countries) / sizeof(string); i++)

		cout << '\t' << countries[i] << endl;



	plus = Add;

	cout << "3855.06 + 74.88 = " << plus(3855.06, 74.88) << endl << endl;

	return 0;

}

In C++, the attribute of the typedef is usually applied as a class, a struct, or an enum. Here are examples:

#include <iostream>

#include <string>

using namespace std;



typedef struct Student;

typedef class Country;



typedef public short SmallNumber;

typedef private unsigned int Positive;

typedef protected double* PDouble;

typedef public string FiveStrings[5];

typedef private double (*Addition)(double value1, double value2);



struct Student

{

	string FirstName;

	string LastName;

};



typedef struct _Empl

{

	string FullName;

	double HourlySalary;

}Employee;



class Country

{

	string Name;

	string Capital;

	string Code;

};



double Add(double x, double y)

{

	double result = x + y;

	return result;

}



typedef enum EmplStatus { esFullTime, esPartTime, esContractor };

typedef Student *PStudent;

typedef Country *PCountry;



int main()

{

	Student pupil;

	Country pais;

	EmplStatus emplst;

	PStudent ptrStd = new Student;

	PCountry pPais = new Country;



	return 0;

}

 
	
 
Home	Copyright � 2005 FunctionX, Inc.	


<think>嗯,用户想了解C/C++typedef的用法。首先,我需要回忆一下typedef的基本概念和常见用途。根据引用资料,typedef主要用于给类型定义别名,提高代码的可读性和可维护性。比如,引用[2]提到typedef可以隐藏笨拙的语法,比如平台相关的数据类型,增强可移植性。 接下来,我需要整理typedef的主要用途。引用[1]和[3]都提到了定义类型别名,特别是处理指针和复杂结构。比如,typedef const char* cpstr,这样在函数参数中使用cpstr会更清晰。另外,引用[3]还提到标准库中使用typedef的例子,如size_t,这有助于跨平台兼容。 然后,要注意typedef和#define的区别。引用[4]指出typedef不是简单的字符串替换,而是定义新类型别名。例如,typedef char* PSTR和#define PSTR char*在连续声明变量时会有不同表现,这一点需要解释清楚。 还要提到typedef在结构体中的应用。引用[5]提到旧版C中需要struct关键字来声明结构体变量,而使用typedef后可以简化。比如,定义MyStruct后可以直接用MyStruct声明变量,而不必写struct关键字。 然后,陷阱部分。引用[1]和[4]都提到,定义指针类型时要注意const的位置。例如,typedef char* Ptr的情况下,const Ptr实际上是常量指针,而不是指向常量的指针,这一点容易出错,需要特别说明。 最后,应用场景总结,包括跨平台兼容、简化复杂类型、统一函数指针类型等。这部分可以结合引用中的例子,如REAL类型根据不同平台定义为float或double,或者简化模板类型如std::string。 用户可能的问题包括typedef与宏的区别、结构体别名、指针类型处理等,需要准备好相关问题。同时,确保回答结构清晰,分点说明,并正确使用LaTeX格式,如$TypeName$,代码块用正确语法。</think>### C/C++ typedef用法详解 #### 一、核心用途 1. **定义类型别名** 为复杂类型创建易于理解的名称,增强代码可读性。例如: ```c typedef unsigned int UINT32; // 定义平台无关的32位无符号整数类型 typedef int (*FuncPtr)(int, int); // 定义函数指针类型$FuncPtr$ ``` 2. **跨平台兼容** 通过条件编译实现类型统一(引用[3]): ```c #ifdef WIN32 typedef double REAL; #else typedef float REAL; #endif ``` 3. **简化复杂结构体声明** 消除冗余的`struct`关键字(引用[5]): ```c typedef struct { int x; int y; } Position; Position p; // 直接使用别名声明变量 ``` 4. **统一函数指针类型** 避免重复书写复杂语法: ```c typedef void (*Callback)(int status); Callback loginHandler; // 声明函数指针变量 ``` #### 二、关键语法规则 - **与`#define`的本质区别** `typedef`是类型别名定义,而`#define`是文本替换。例如: ```c typedef char* Ptr; #define CharPtr char* const Ptr p1; // 等效于char* const p1(常量指针) const CharPtr p2; // 等效于const char* p2(指向常量的指针) ``` - **指针类型的特殊处理** 定义指针类型时需显式添加`const`(引用[1]): ```c typedef const char* CPSTR; // 正确:指向常量字符的指针 int compare(CPSTR a, CPSTR b); // 参数类型明确 ``` #### 三、典型应用场景 1. **隐藏平台差异** 如标准库的`size_t`类型(引用[3]) 2. **简化模板语法** 例如`std::string`本质是: ```cpp typedef basic_string<char> string; ``` 3. **增强代码可维护性** 集中管理类型定义,便于批量修改 #### 四、常见陷阱 1. **错误理解作用域** `typedef`受块作用域限制,与变量声明类似 2. **错误添加存储类修饰符** ```c typedef static int StaticInt; // 错误!不能与static共用 ``` #### 代码示例 ```cpp // 定义函数指针类型 typedef int (*Comparator)(const void*, const void*); // 使用示例 int numeric_compare(const void* a, const void* b) { return *(int*)a - *(int*)b; } Comparator cmp = numeric_compare; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值