【发布时间】:2020-10-27 16:45:12
【问题描述】:
这是我在stackowerflow 中的第一个问题。所以我很兴奋:) 我正在尝试在 C 中练习多态性。我读过很多文章。我用我所理解的编写了一个小示例代码。我的目标是创建一个形状类。此类包括字段和长度方法。派生自该类的矩形和圆形类对字段和长度方法进行自己的计算。
但是编译时出现问题: enter image description here 在 OOP_in_C_example_3_polymorphism_3.exe 中的 0x000000000000000A 处引发异常:0xC0000005:访问冲突执行位置 0x000000000000000A。
当我删除其中一行时它会变得更好。但这一次它根据最后调用的构造函数进行操作: enter image description here
我哪里有问题?
形状.h:
#include <stdint.h>
struct Vtable;
typedef struct{
struct Vtable* vptr;
uint16_t x;
uint16_t y;
}Shape;
struct Vtable {
void(*area)(Shape* me);
void(*lenght)(Shape* me);
};
inline void area(Shape* me) {
(*me->vptr->area)(me);
}
inline void lenght(Shape* me) {
(*me->vptr->lenght)(me);
}
void shape_ctor(Shape* me, int x, int y);
shape.c:
#include "shape.h"
void shape_ctor(Shape* me,int x, int y) {
struct Vtable vtbl = { &area,&lenght };
me->vptr = &vtbl;
me->x = x;
me->y = y;
}
rect.h:
#include "shape.h"
typedef struct {
Shape super;
uint16_t en;
uint16_t boy;
}rect;
void rect_ctor(rect* me, uint16_t x, uint16_t y, uint16_t en, uint16_t boy);
rect.c:
#include "rect.h"
#include <stdio.h>
void rect_lenght(void* me);
void rect_area(void* me);
void rect_ctor(rect* me,uint16_t x, uint16_t y, uint16_t en, uint16_t boy) {
struct Vtable vtbl = { &rect_area, &rect_lenght };
shape_ctor(&me->super, x, y);
me->super.vptr = &vtbl; //override vptr
me->en = en;
me->boy = boy;
}
void rect_lenght(void* me) {
rect* me_ = (rect*)me; //downcast işlemi
printf("rectangle lenght: %d\n",(me_->en + me_->boy) * 2);
}
void rect_area(void* me) {
rect* me_ = (rect*)me; //downcast işlemi
printf("rectangle area: %d\n", (me_->en)*(me_->boy));
}
circle.h:
#include "shape.h"
typedef struct {
Shape super;
uint16_t radius;
}circle;
void circle_ctor(circle* me, uint16_t x, uint16_t y, uint16_t r);
circle.c:
#include "circle.h"
#include <stdio.h>
void circle_lenght(void* me);
void circle_area(void* me );
void circle_ctor(circle* me, uint16_t x, uint16_t y, uint16_t r) {
struct Vtable vtbl = {&circle_area,&circle_lenght};
shape_ctor(&me->super, x, y);
me->super.vptr = &vtbl;
me->radius = r;
}
void circle_lenght(void* me) {
circle* me_ = (circle*)me;
printf("circle lenght: %f\n", (me_->radius) * (2) * (3.14));
}
void circle_area(void* me){
circle* me_ = (circle*)me;
printf("circle area: %f\n", (me_->radius) * (me_->radius) * (3.14));
}
main.c:
#include <stdio.h>
#include "rect.h"
#include "circle.h"
int main() {
rect k1;
circle d1;
rect_ctor(&k1, 10, 10, 15, 20);
circle_ctor(&d1, 10, 10, 5);
k1.super.vptr->lenght(&k1);
d1.super.vptr->lenght(&d1);
}
【问题讨论】:
-
请将错误添加为文本而非图像。错误看起来像运行时异常而不是编译错误。
-
But there is a problem during compilation: enter image description here: 看来他是在执行过程中,而不是在编译过程中,反正我不明白你怎么能不出错地编译那个代码 -
访问冲突意味着您正在写入内存中不属于您的位置。查找创建的缓冲区对于您正在写入的内容而言太小,或者未分配内存的指针。而且,我同意第一个评论者的观点,请考虑编辑您的代码以将错误消息作为文本包含在帖子中,而不是隐藏在图片链接中。顺便说一句,
lenght拼写为length:) 否则,这个问题做得很好。 (+1)
标签: c oop polymorphism