在要打印的结构中添加函数指针 [英] Adding a function pointer within a struct to print

查看:45
本文介绍了在要打印的结构中添加函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中执行以下操作的正确方法是什么?

What would be the proper way to do the following in C?

typedef struct Book {
    char* title;
    unsigned int year;
    void // print ??;
} Book;

void print_book(Book *book)
{
    printf("{\n\ttitle: \"%s\",\n\tyear: %d\n}\n", book->title, book->year);
}

int main(int argc, char * argv[])
{
    Book romeo = {
        .title="Rome & Juliet",
        .year=2000
    };
    print_book(&romeo); // how can I do romeo.print() instead?
}

定义结构成员 print 以指向 print_book 函数的正确方法是什么?

What would be the correct way to define the struct member print to point to the print_book function?

推荐答案

声明它的标准方法是:

typedef struct Book {
    char* title;
    unsigned int year;
    void (*func)(struct Book *book);
} Book;

我不得不使用 struct Book 而不是 Book ,因为尚未定义 Book 类型.

I had to use struct Book instead of Book because the Book type has not yet been defined.

一种更好的方法是:

typedef struct Book Book;
struct Book {
    char* title;
    unsigned int year;
    void (*func)(Book *book);
};

这会在结构定义之前创建 typedef ,因此可以在结构内部使用 typedef 名称.

This creates the typedef before the structure definition, so the typedef name can then be used inside the structure.

要调用它,您可以执行以下操作:

To call it, you can do:

Book romeo;
romeo.func = print_book;
(*romeo.func)(&romeo);

在这种情况下,您可以选择将& 运算符应用于 print_book ,例如 romeo.func =& print_book; .两者是等效的.

In this context, you can optionally apply the & operator to print_book, e.g. romeo.func = &print_book;. The two are equivalent.

请注意,我已经将函数指针称为 func ,但是您当然可以使用任何您喜欢的名称(例如,如您帖子中的 print ).

Note that I've called the function pointer func, but you can of course use any name you like (e.g. print, as in your post).

这篇关于在要打印的结构中添加函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆