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)

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM