Struct多态用法

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;  
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C语言是一种静态类型语言,它不像面向对象语言那样直接支持多态。但是,我们可以通过结构体、函数指针和类型转换等技巧来实现类似于多态的效果。 一种常见的方法是使用函数指针数组。我们可以定义一个基类结构体,其中包含一个函数指针数组,每个函数指针指向一个虚函数。然后,派生类可以继承这个基类结构体,并对其中的虚函数进行重写。在运行时,我们可以根据实际对象的类型来动态地选择调用哪个虚函数。 以下是一个简单的示例代码,演示了如何使用函数指针数组实现多态: ```c #include <stdio.h> // 基类结构体 struct Animal { const char* name; void (*speak)(); }; // 派生类结构体 struct Dog { struct Animal base; // 继承基类 }; // 虚函数的具体实现 void speak_dog() { printf("Woof!\n"); } int main() { struct Dog my_dog; my_dog.base.speak = speak_dog; // 继承虚函数 my_dog.base.speak(); // 动态调用虚函数 return 0; } ``` 在这个例子中,我们定义了一个基类结构体 `Animal`,其中包含一个函数指针 `speak`,指向一个虚函数。然后,我们定义了一个派生类结构体 `Dog`,它继承了 `Animal`。在 `main()` 函数中,我们创建了一个 `Dog` 对象,并将 `speak()` 函数指针指向 `speak_dog()` 函数,这样就实现了多态。最后,我们调用 `speak()` 函数,它会动态地调用 `speak_dog()` 函数。 需要注意的是,这种实现方法并不是真正的多态,因为它没有提供运行时的类型检查和类型转换。在实际开发中,建议使用面向对象语言来实现多态

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值