c - 如何将 *this 指针隐式传递给结构中的函数指针

标签 c function-pointers

我写一个字符串结构如下。

typedef struct string string;
struct string
{
    int length;
    char* content;
    void (*init)(string*, const char*);
    void (*print)(string*);
};
void print(string* a)
{
    printf("%s", a->content);
}
void init(string* a, const char* b)
{
    a->init = init;
    a->print = print;
    a->length = strlen(b);
    a->content = (char*)malloc(sizeof(char) * strlen(b));
    strcpy(a->content, b);

}

int main()
{
    string a;
    init(&a, "Hello world!\n");
    a.print(&a);
}

我试图在这里模仿 ooc,但我想不出更好的方法。例如,有没有一种方法可以使 print(&a) 像:a.print,而不将指向自身的指针传递给函数,就像隐式 *this 指针在其他语言中所做的那样?

最佳答案

is there a possible way to make print(&a) like: a.print, without passing a pointer to itself to the function, like an implicit *this pointer does in other language?

你不能


警告

a->content = (char*)malloc(sizeof(char) * strlen(b));
strcpy(a->content, b);

您需要为空结尾的字符再分配 1 个,否则 strcpy 会以未定义的行为从分配的 block 中写出

a->content = malloc(a->length + 1);

strlen 已经保存在 a->length 中,所以我使用它并且乘以 sizeof(char) 是没有用的,因为它根据定义为 1

关于c - 如何将 *this 指针隐式传递给结构中的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55194523/

相关文章:

c++ - 在这种情况下是否需要内存屏障或只是一个 volatile

c++ - 函数指针作为模板参数

c - C 中的 "this"指针(不是 C++)

c++ - 采用函数指针的函数模板的干净实现

C++ 可变参数模板基础

c - memmove 和 malloc 线程安全吗?

c - 编译 C 程序有多容易?

c - 是否仍然值得尝试在 C 中为 sqrt() 创建优化?

c - 从函数中获取数组的计数

c# - 如何将 C# 函数指针传递给 CLI/C++ 代码?