C++typedef用法

搞懂了c++创始人写的<the design and evolution of cpp>中的下面这个例子, 有助于你理解typdef:

typedef int P();
typedef int Q();
class X {
    static P(Q); // 等价于`static int Q()`, Q在此作用域中不再是一个类型
    static Q(P); // 等价于`static int Q(int ())`, 定义了一个名为Q的function
};

这是一个极好的例子, 先问一下 typedef int P()到底做了什么? 其实是:

declares a function type P as returning an int and taking no arguments.

 

1. 官方定义

初次接触此类typedef用法的程序员直观上理解这个例子比较困难, 我们来看一下typedef的官方定义:

Typedef does not work like typedef [type] [new name]. The [new name] part does not always come at the end.

You should look at it this way: if [some declaration] declares a variable, typedef [same declaration] would define a type.

看我标黑的这句话, 总结一下就是: 任何声明变量的语句前面加上typedef之后,原来是变量的都变成一种类型不管这个声明中的标识符号出现在中间还是最后.

 

2. 隐藏技能

typedef 定义的新类型, 使用时可以省略括号.

什么意思?

typedef int NUM;
NUM a = 10; // 也可写成`NUM(a) = 10;
NUM(b) = 12; // 也可写成`NUM b = 12;

 

3. 举例

先从初级的开始:

整形

typedef int x; // 定义了一个名为x的int类型

结构体

typedef struct { char c; } s; // 定义名为s的struct类型

指针

typedef int *p; //定义了一个名为p的指针类型, 它指向int (中文描述指针好累)

接下来是高级的(注意标识符不一定在最后):

数组

typedef int A[];  // 定义一个名为A的ints数组的类型

函数

typedef int f(); // 定义一个名为f, 参数为空, 返回值为int的函数类型
typedef int g(int); // 定义一个名为g, 含一个int参数, 返回值为int行的函数类型

现在回过头看:

typedef int P();
static P(Q); 

 

应该就比较好理解了, P是一个新定义的function类型, 它返回值为int, 无参数

根据我的第2点说明, P(Q); 实际上等价于P Q, 声明Q是一个返回值为int, 无参数的函数.

这玩意有什么用呢?

我们都知道C++语言里, 函数都是先声明后使用的(除非在使用之前定义), 看以下例子:

#include <iostream>
#include <stdio.h>
#include <string>

typedef int P(); // 简单的
typedef void Q(int *p, const std::string& s1, const std::string& s2, size_t size, bool is_true); // 复杂的
class X {
public:
    P(eat_shit); // 等价于声明`int eat_shit();`
    Q(bullshit); // 等价于声明`void bullshit(int *p, const string& s1, const string& s2, size_t size, bool is_true);`
};

int main() {
    X *xx;
    printf("shit ret: %d\n", xx->eat_shit());
    int a[] = {1, 3, 4, 5, 7};
    xx->bullshit(a, "foo", "bar", sizeof(a)/sizeof(int), true);
}

int X::eat_shit() {
    return 888;
}

void X::bullshit(int *p, const std::string& s1, const std::string& s2, size_t size, bool is_true) {
    std::cout << "s1: " << s1 << ", s2: " << s2 << ", size: " << size << std::endl;
    printf("elems:\n");
    for(int i = 0; i < size; i++) {
        printf("%d %s",  *p++, (i == size-1) ? "" : ",");
    }
    printf("\n");
}

怎么样, typedef技能点亮了吗? :)

 

转自:typedef和#define 的区别? - 知乎 (zhihu.com)

 

 

 

posted @ 2021-12-29 22:58  补码  阅读(821)  评论(0编辑  收藏  举报