我可以在 C 结构中定义函数吗?

标签 c function structure

<分区>

我正在尝试将一些 C++ 代码转换为 C,但我遇到了一些问题。 如何在结构中定义函数?

像这样:

 typedef struct  {
    double x, y, z;
    struct Point *next;
    struct Point *prev;
    void act() {sth. to do here};
} Point;

最佳答案

不,您不能在 C 中的 struct 中定义函数。

你可以在 struct 中有一个函数指针,但是有一个函数指针与 C++ 中的成员函数有很大不同,即没有隐式的 this 指针指向包含的 struct 实例。

人为的例子(在线演示 http://ideone.com/kyHlQ ):

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

struct point
{
    int x;
    int y;
    void (*print)(const struct point*);
};

void print_x(const struct point* p)
{
    printf("x=%d\n", p->x);
}

void print_y(const struct point* p)
{
    printf("y=%d\n", p->y);
}

int main(void)
{
    struct point p1 = { 2, 4, print_x };
    struct point p2 = { 7, 1, print_y };

    p1.print(&p1);
    p2.print(&p2);

    return 0;
}

关于我可以在 C 结构中定义函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12642830/

相关文章:

c - 包含字母、空格和整数的 sscanf

c - 如何在 C 编程中创建循环内生成的变量数组

c - 如何在共享对象库中共享变量

function - 函数名前面的解引用运算符有什么作用?

c - 如何存储从 C 语言文件中读取的结构?

c++ - 体验在 Raspberry Pi 上为 PCF8575 I/O 扩展器编写 C 代码

c++ - 模板成员函数参数推导

php - 如何将这个php slugify函数重写到mysql?

c - 我做错了什么?下面的代码不会将结构化数据的最后一条记录从 .dat 文件复制到 C 中的另一个 .dat 文件

c++ - 创建一个包含汽车年份和制造商的动态数组但无法保存我的第一个输出