简体   繁体   English

如何在 C function 结构上进行此更改?

[英]How can i make this change on C function struct?

I've been trying to emulate Python instance construction on C, but i cant find a way to get the struct name backwards to the function and give it as parameter我一直在尝试在 C 上模拟 Python 实例构造,但我找不到将结构名称向后获取到 ZC1C425268E68385D1AB5074C17A94F14 的方法

typedef struct queue {
    .
    .
    ssize_t (*add)(struct queue *, int);
} queue;

ssize_t add(queue *self, int value)
{
    /* Add a element to the queue */
}

int main(void)
{
    queue *clients = createQueue(5); /* Here i create the queue struct */

    clients.add(5); /* I want to convert this instruction to "clients.add(&clients, 5);" */
}

I've triyed to use macros but I've found i can't use regex or something like that我试过使用宏,但我发现我不能使用正则表达式或类似的东西

It is difficult to 'emulate' an object language in a non object language like C, but simple to do in C++ like:用非 object 语言(如 C)很难“模拟” object 语言,但在 ZF6F877C9FDCF18B666Z 语言中很容易做到

struct queue { // a 'struct' is a 'class' where all is 'public' by default
    .
    .
    ssize_t add(int); // in C++ 'this' corresponding to 'self' does not have to be explicitly placed in the params list
};

ssize_t queue::add(int value)
{
    /* Add a element to the queue */
    return ...a ssize_t...;
}

int main(void)
{
    queue * clients = createQueue(5); /* Here i create the queue struct */

    clients->add(5); // '->' rather than '.' because clients is a 'queue*' rather than a 'queue'
}

The corresponding of Python 'self' is named 'this' in C++ and you do not not have to place it explicitly in the parameter list, it is implicit. Python 'self' 的对应在 C++ 中被命名为 'this' 并且您不必将其显式放置在参数列表中,它是隐式的。

Note in C++ there is no garbage collector like in Python, probably createQueue allocate the queue in the heap, in that case if you want to liberate the allocated memory before the end of the execution you have to do delete queue;注意在 C++ 中没有像 Python 中那样的垃圾收集器,可能createQueue在堆中分配队列,在这种情况下,如果您想释放分配的 ZCD69B4957F06CD818D7BF3D61980E21 执行结束之前必须执行delete queue;

And to finish there is an implicit return 0;最后还有一个隐式的return 0; at the end of main if you do not return by yourself如果您不自己返回,则在main结束时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM