// C++Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//typedef与#define的区别:
typedef int* TPINT;
#define DPINT int*
int _tmain(int argc, _TCHAR* argv[])
{
int a = 1, b = 2;
//使用typedef的TPINT,两个都是指针
TPINT tpa, tpb;
tpa = &a;
tpb = &b;
cout<<"a by pointer: "<<*tpa<<" b by pointer: "<<*tpb<<endl;
//使用#define的只是简单的替换,第二个并不是pointer
//这句话相当于int *dpa, dpb;
//dpb是int类型的变量!!!
DPINT dpa, dpb;
dpa = &a;
dpb = b;
cout<<"a by pointer: "<<*dpa<<"b by value: "<<dpb<<endl;
system("pause");
return 0;
}
结果:typedef int INT16 typedef long INT32但是,有的机器上变成short位16位,int 32位,long变成了64位,那么我们如果想要运行的话,只能用short和int了,而我们使用了typedef,就可以很轻易的改typedef,而完全不需要大改项目:
typedef short INT16 typedef int INT32
std::list<MyObj> objList;
typedef std::list<MyObj> ObjList; ObjList objlist;
// C++Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//函数
void testfunc(int x)
{
cout<<"x = "<<x<<endl;
};
int _tmain(int argc, _TCHAR* argv[])
{
//定义一个函数指针
void (*pfunc1)(int x);
void (*pfunc2)(int x);
pfunc1 = testfunc;
pfunc2 = testfunc;
pfunc1(1);
pfunc2(2);
system("pause");
return 0;
}
这个函数目前只有一个参数,看起来都够麻烦了,那么如果有一大堆的参数,简直不忍直视!!!// C++Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//函数
void testfunc(int x)
{
cout<<"x = "<<x<<endl;
};
//使用typedef来重命名函数指针
typedef void (*pFunc)(int x);
int _tmain(int argc, _TCHAR* argv[])
{
//这下定义一个函数指针就简单多啦!!!
pFunc pfunc1;
pFunc pfunc2;
pfunc1 = testfunc;
pfunc2 = testfunc;
pfunc1(1);
pfunc2(2);
system("pause");
return 0;
}
结果:typedef struct tpoint
{
int x;
int y;
}Point;
Point pt;// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#define DPINT int*
typedef int* PINT;
int _tmain(int argc, _TCHAR* argv[])
{
int i1 = 2;
int i2 = 3;
const PINT pi1 = &i1;
const PINT pi2 = &i2;
const DPINT pi3 = &i1;
//pi1 = &i2;这句是错误的,因为pi1整体为一个数据类型,Int*,即指针本身为const。
//而指针指向的内容却是可变的
*pi1 += 3;
//对于pi3,为单纯的替换,即const int* pi3,此处const为底层const,修饰int*所指向的内容。所以指针本身是可以修改指向的
pi3 = &i2;
system("pause");
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/puppet_master/article/details/48376573