Struct多态用法
Struct和Class有很多相通之处,都是一个数据类型的集合。Struct也同样可以实现Class的多态用法。
关键之处是指针的指向和地址的使用。
下面是两个例子,主要的点在于结构体的写法,这个是实现多态的基础。
#include <stdio.h>
struct S1
{
int temp1;
int temp2;
};
struct S2
{
S1 ss1;
int temp3;
int temp4;
};
int main()
{
S2 s2 = {1,2,3,4};
S1 *s1 = &s2.ss1;
S2 *ps2 = (S2*)s1;
printf("S2 = %d\n",s2.ss1.temp1);
printf("s2 address =%p\n",&s2);
printf("s2.ss1 address =%p\n",&s2.ss1);
printf("s2.ss1.temp1 address =%p\n",&(s2.ss1.temp1));
printf("ps2 = %d\n",ps2->ss1.temp1);
printf("ps2 address =%p\n",ps2);
printf("ps2->ss1 address =%p\n",&ps2->ss1);
printf("ps2->ss1.temp1 address =%p\n",&(ps2->ss1.temp1));
return 0;
}
具体针对多态的例子
#include <stdio.h>
struct Shape {
void (*draw)() ;
} ;
struct Circle {
struct Shape shape;
int radius;
} ;
struct Rectangle {
struct Shape shape;
int width;
int height;
} ;
void drawNothing() {
printf("Draw nothing...\n") ;
}
void drawCircle() {
printf("Drawing a circle...\n") ;
}
void drawRectangle() {
printf("Drawing a rectangle...\n") ;
}
void Process(Shape* shape)
{
shape->draw();
}
int main() {
struct Circle circle = {drawCircle, 1};
struct Rectangle rectangle = {drawRectangle, 2, 3};
struct Shape *shape = (struct Shape*)&circle;
Process(shape);
shape = (struct Shape*)&rectangle;
Process(shape);
return 0;
}