• C++进阶2. typedef用法


    C++ 中的typedef用法 20131011

    Typedef在C++中是一个关键字,他的用法有多重,但是自己又说不全面,所以整理一下:

    1.用类型的别名

             typedef char* PChar; 这里就是使用PChar 代替程序中的char*,在编写程序的时候PChar a 等价于char * a;

             不知指针, 如 typedef int INT4;

    2.为结构体的别名

             typedef struct test1{

                       char a;

                       int b;

             }Test;

             也就是Test 等价于struct test1

             使用的时候我们使用 Test a;等价于 struct test1 a;

             编程的时候,因为Java的原因,对于程序的内存有点混乱,

             Test t1; t1.a = 100;

             Test t2; t2 = t1; t2.a = 99; 其实这里的复制已经是两个对象,而不是同一个对象。

             但是在Java中,不是这个样子的,因为所有的对象都是保存在堆中的,名字只是一个指向堆中对象的引用。

    class Test{

        int a;

        Test(){}

        Test(Test t){

            this.a = t.a;

        }

    }

    public class TestMain {

        public static void main(String[] args) {

            // TODO Auto-generated method stub

            Test t1 = new Test();

            t1.a = 10;

            Test t2 = t1;

            t2.a = 19;

            Test t3 = new Test(t1);

            t3.a = 199;

            System.out.println(t1.a ); //19

            System.out.println(t2.a );//19

            System.out.println(t3.a );//199

        }

    }

    3.通过别名实现平台的兼容性

        如定义REAL类型数据,但是不同的平台上可能不支持double long double 等等,我们在程序中同意使用REAL,在程序中修该typedef 为支持的数据类型,而不用修改代码。

    4.为复杂的函数指针或者类型去一个简单的名字

        typedef int (* PFun) (int* p);

        这表示的是一个函数指针,返回值是int类型的,并且参数是 int* 的函数指针。我们在程序中如果需要使用到这种类型的函数指针。

        int (* pfun1) (int* p);

        int (* pfun2) (int* p);

        简单的写法 PFunc pfun1, pfun2;即可。

    追梦的飞飞

    于广州中山大学 20131011

    HomePage: http://yangtengfei.duapp.com

  • 相关阅读:
    C51学习笔记
    Keil C51与Keil ARM共存
    keil c51笔记
    css实现三角形
    微信小程序倒计时实现
    微信小程序公共组件的引用与控制
    mac上查找nginx安装位置
    charles抓取移动端app数据
    封装react组件——三级联动
    前端基础(http协议相关篇)
  • 原文地址:https://www.cnblogs.com/hbhzsysutengfei/p/3409498.html
Copyright © 2020-2023  润新知