Tag: 多态性

从派生中调用基函数

我在C中使用了本教程示例inheritance和多态 ,因为我根据我的确切要求对其进行了自定义,当我尝试调用基函数时它会抛出错误。 问题:为什么它在employee.c的第8行和可能的解决方案中失败 ((Employee *)self)->super.display(self); // Sementation fault: 11 下载项目 main.c中 #include “person.h” #include “employee.h” #include int main() { Person* person = newPerson(“John Doe”); Employee* employee = newEmployee(“Jane Doe”, “Acme”, 40000); person->display(person); // displaying Person object puts(“——“); employee->display((Person*)employee); // displaying employee info return 0; } Person.h #ifndef _PERSON_H #define _PERSON_H #include typedef struct Person Person; […]

是否需要不兼容的指针来实现C中的多态性

我尝试使用以下代码在C中模拟C ++的多态性: #include typedef struct Base { void (*out) (void); } Base; typedef struct Derived { Base base; int x; } Derived; void base_out() { printf(“base\n”); } void derived_out() { printf(“derived\n”); } void foo(void) { Derived d; Base b; b.out = base_out; d.base.out = derived_out; Base *p; p = &b; p->out(); //warning: assignment from incompatible […]

多态性(C中)

可能重复: 如何在C中模拟OO风格的多态? 我试图用我所知道的语言中的例子来更好地理解多态的概念; C中有多态吗?