面向对象C编程--虚函数

在C语言中没有面向对象的概念,也没有原生的虚函数,但可以通过结构体和函数指针实现类似于虚函数的功能。

下面是一个简单的示例程序:

#include 

// 定义基类
typedef struct {
    void (*show)(void); // 声明虚函数
} Base;

// 定义派生类
typedef struct {
    Base base; // 派生类包含基类
    int num;
} Derived;

// 定义基类的虚函数实现
void base_show(void) {
    printf("This is the base class.\n");
}

// 定义派生类的虚函数实现
void derived_show(void) {
    printf("This is the derived class.\n");
}

int main() {
    Base *base_ptr;
    Derived derived;
    
    // 初始化基类指针
    base_ptr = &derived.base;
    
    // 设置基类的虚函数为派生类的虚函数
    base_ptr->show = derived_show;
    
    // 调用虚函数,输出 "This is the derived class."
    base_ptr->show();
    
    // 设置基类的虚函数为基类的虚函数
    base_ptr->show = base_show;
    
    // 调用虚函数,输出 "This is the base class."
    base_ptr->show();
    
    return 0;
}

在这个示例程序中,我们定义了一个 Base 结构体作为基类,它只有一个虚函数 show。我们还定义了一个 Derived 结构体作为派生类,它包含了一个 Base 类型的成员变量和一个整型 num。

我们在程序中定义了基类的虚函数实现 base_show 和派生类的虚函数实现 derived_show。在 main() 函数中,我们创建了一个派生类对象 Derived derived,并通过基类指针 base_ptr 引用该对象的基类部分。

我们通过将 base_ptr->show 设置为派生类的虚函数 derived_show 来重载基类的虚函数。这样,当我们调用 base_ptr->show() 时,会执行派生类的虚函数实现,输出 “This is the derived class.”。然后,我们又将 base_ptr->show 设置为基类的虚函数 base_show,使得再次调用 base_ptr->show() 时执行基类的虚函数实现,输出 “This is the base class.”。

总之,通过结构体和函数指针,我们可以模拟类的继承和虚函数的重载。

【最后一个bug】多平台都有更新和发布,大家可以一键三连,关注+星标,不错过精彩内容~
面向对象C编程--虚函数_第1张图片

你可能感兴趣的:(c语言,算法,arm开发,开发语言)