In C++, the typedef keyword allows you to create an alias for a data type. The formula to follow is:
typedef [attributes] DataType AliasName;
The typedef keyword is required. The attribute is not.
例子:
typedef short SmallNumber;
typedef unsigned int Positive;
typedef double* PDouble;
typedef string FiveStrings[5];
1. In typedef short SmallNumber, SmallNumber can now be used as a data type to declare a variable for a small integer.
2. In the second example, typedef unsigned int Positive, The Positive word can then be used to declare a variable of an unsigned int type.
3. After typedef double* PDouble, the word PDouble can be used to declare a pointer to double.
4. By defining typedef string FiveStrings[5], FiveStrings can be used to declare an array of 5 strings with each string being of type string.
SmallNumber temperature = -248;
Positive height = 1048;
PDouble distance = new double(390.82);
FiveStrings countries = { "Ghana", "Angola", "To“,"Tunisia", "Cote d'Ivoire" };
值得注意的写法
typedef char* PSTR, CHAR;
CHAR为char型,所以更好的写法是
typedef char *PSTR, CHAR; 或者 typedef char CHAR, *PSTR;
(2) 定义函数类型别名
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。
例子:
typedef double (*Addition)(double value1, double value2);
double Add(double x, double y)
{
double result = x + y;
return result;
}
Addition plus;
plus = Add;
plus(3855.06, 74.88);
例子2:(msdn上)
The following example provides the type DRAWF for a function returning no value and taking two int arguments:
typedef void DRAWF( int, int );
After the above typedef statement, the declaration
DRAWF box;
would be equivalent to the declaration
void box( int, int );
(3)
总结typedef的语法为:
More generally, after the word “typedef”, the syntax looks exactly like what you would do to declare a variable of the existing type with the variable name of the new type name. Therefore, for more complicated types, the new type name might be in the middle of the syntax for the existing type. For example:
typedef char (*pa)[3]; // "pa" is now a type for a pointer to an array of 3 chars
typedef int (*pf)(float); // "pf" is now a type for a pointer to a function which takes 1 float argument and returns an int
没有评论:
发表评论