C 语言中的 OOP,实现和错误 [英] OOP in C, implementation and a bug
问题描述
我正在尝试在 C 中探索 OOP.然而,我是一个 C n00b 并且想挑选 stackoverflow 的聪明大脑:)
I am trying to explore OOP in C. I am however a C n00b and would like to pick the brilliant brains of stackoverflow :)
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct speaker {
void (*say)(char *msg);
} speaker;
void say(char *dest) {
printf("%s",dest);
}
speaker* NewSpeaker() {
speaker *s;
s->say = say;
return s;
}
int main() {
speaker *s = NewSpeaker();
s->say("works");
}
但是我从中得到了一个段错误,如果我从 say 中删除所有 args 并使其无效,我可以让它正常工作.我当前的代码有什么问题?
However I'm getting a segfault from this, if I however remove all args from say and make it void, I can get it to work properly. What is wrong with my current code?
还有.虽然这在 C 中实现了一种对象形式,但我试图通过继承来进一步实现它,甚至覆盖/重载方法.您认为我如何实现这样的功能?
Also. While this implements a form of object in C, I'm trying to further implement it with inheritance, and even overriding/overloading of methods. How do you think I can implement such?
谢谢!
推荐答案
在您的代码中,NewSpeaker()
实际上并未创建新"扬声器.您需要使用内存分配函数,例如 malloc
或 calloc
.
In your code, NewSpeaker()
doesn't actually create a "new" speaker. You need to use a memory allocation function such as malloc
or calloc
.
speaker* NewSpeaker() {
speaker *s = malloc(sizeof(speaker));
s->say = say;
return s;
}
没有赋值,例如 malloc
的返回值,s
被初始化为堆栈上的垃圾,因此是段错误.
Without assigning the value from, for example, the return value of malloc
, s
is initialized to junk on the stack, hence the segfault.
这篇关于C 语言中的 OOP,实现和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!