本文已参与「新人创作礼活动」,一起开启掘金创作之路。
一、今日课题
二、实战演练
typedef is a reserved keyword in the C and C++ programming languages. It is used to create an alias name for another data type.As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, but is just as common in providing specific descriptive type names for integer data types of varying lengths.
1)有何用?
- 定义一种类型的别名,而不只是简单的宏替换。可以用作同时声明指针型的多个对象。
- 用在旧的C的代码中(具体多旧没有查),帮助struct。
- 用typedef来定义与平台无关的类型。
- 为复杂的声明定义一个新的简单的别名。
2)怎么用?
#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);
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;
system("pause");
return 0;
}
3)前方高能
陷阱一:
记住,typedef是定义了一种类型的新别名,不同于宏,它不是简单的字符串替换。比如:
先定义:
typedef char* PSTR;
然后:
int mystrcmp(const PSTR, const PSTR);
const PSTR实际上相当于const char*吗?不是的,它实际上相当于char* const。
原因在于const给予了整个指针本身以常量性,也就是形成了常量指针char* const。
简单来说,记住当const和typedef一起出现时,typedef不会是简单的字符串替换就行。
陷阱二:
typedef在语法上是一个存储类的关键字(如auto、extern、mutable、static、register等一样),虽然它并不真正影响对象的存储特性,如:
typedef static int INT2; //不可行
编译将失败,会提示“指定了一个以上的存储类”。