首页 > 代码库 > 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的使用