首页 > 代码库 > C++ typedef的使用
C++ typedef的使用
第一种是定义别名,实例代码如下:
// TypedefDemo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; int main() { typedef char* PCHAR; char ch1 = ‘a‘; PCHAR a = &ch1; cout << *a << endl; system("pause"); return 0; }
第二种是用来帮助struct。在旧的C代码中使用多。
在C++中,使用struct如下:
// TypedefDemo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; struct tagPoint { int x; int y; }; int main() { tagPoint *point = new tagPoint(); cout << point->x << "------------>" << point->y << endl; delete point; system("pause"); return 0; }
但是在C中,就必须这样使用,见point定义这一行。
// TypedefDemo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; struct tagPoint { int x; int y; }; int main() { struct tagPoint *point = new tagPoint(); cout << point->x << "------------>" << point->y << endl; delete point; system("pause"); return 0; }
所以就出现了typedef的辅助。
// TypedefDemo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; typedef struct tagPoint { int x; int y; }POINT; int main() { POINT *point = new POINT(); cout << point->x << "------------>" << point->y << endl; delete point; system("pause"); return 0; }
第三种方法是定义函数指针。此处没有举例,之前文章有说明。
C++ typedef的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。