一类别型的指针可以随便转换成另一种指针吗
一种类型的指针可以随便转换成另一种指针吗?
先上代码,二楼描述问题
先上代码,二楼描述问题
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct shape;
struct shape_ops
{
/*返回几何体的面积*/
float (*so_area)(struct shape*);
/*返回几何体的周长*/
int (*so_perimeter)(struct shape*);
};
struct shape
{
int* s_type;
char* s_name;
struct shape_ops* s_ops; /*虚接口,所有子类必须实现*/
};
float shape_area(struct shape* s) /*求形状面积*/
{
return s->s_ops->so_area(s);
}
int shape_perimeter(struct shape* s) /*求周长*/
{
return s->s_ops->so_perimeter(s);
}
/*三角形*/
struct triangle
{
struct shape t_base;
int t_side_a;
int t_side_b;
int t_side_c;
};
float triangle_area(struct shape* s) /*三角形面积,用海伦公式*/
{
struct triangle* t=(struct triangle*)s;
int a=t->t_side_a;
int b=t->t_side_b;
int c=t->t_side_c;
float p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
int triangle_perimeter(struct shape* s) /*三角形周长*/
{
struct triangle* t=(struct triangle*)s;
int a=t->t_side_a;
int b=t->t_side_b;
int c=t->t_side_c;
return a+b+c;
}
struct shape_ops triangle_ops= /*对父类虚接口的实现*/
{
triangle_area,
triangle_perimeter,
};
struct triangle* triangle_create(int a,int b,int c) /*创建三角形*/
{
struct triangle* ret=(struct triangle*)malloc(sizeof (*ret));
ret->t_base.s_name="triangle";
ret->t_base.s_ops=&triangle_ops;
ret->t_side_a=a;
ret->t_side_b=b;
ret->t_side_c=c;
return ret;
}
/*矩形*/
struct rectangle
{
struct shape r_base;
int r_width;
int r_height;
};
float rectangle_area(struct shape* s) /*矩形面积*/
{
struct rectangle* r=(struct rectangle*)s;
return r->r_width*r->r_height;
}
int rectangle_perimeter(struct shape* s)/*矩形周长*/
{
struct rectangle* r=(struct rectangle*)s;