c - 有没有办法在 C 中巧妙地创建一个函数,使其在不同的参数值中执行不同的函数?

标签 c gcc struct shapes unions

😄

我必须创建两个结构,即矩形和椭圆形,其中矩形结构包含其长度和宽度,椭循环结构包含其半短轴和半长轴的长度。然后我必须创建一个 union 形状,其中包含上述两个结构作为其成员。然后,我必须创建一个通用函数“区域”,它计算并集的面积(根据传递给函数的参数计算矩形或椭圆形)。我目前使用菜单驱动的方法并使用 switch case 来处理上述问题(问题后附有代码)。

我想创建一个智能函数,它将并集作为参数,并根据并集中存储的结构来计算面积。

代码

typedef struct rect{
    int l,b;
}r;
typedef struct oval{
    int x,y;
}o;
union shape{
    r r1;
    o o1;
}sh;
void area(int a);
void main()
{
    int ch;
    int a;
    printf(" 1.Area of rect\n 2.Area of oval\n 3.EXIT");
    while(1){
        printf("\nEnter your choice: ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:a=0;
                area(a);
                break;
            case 2:a=1;
                area(a);
                break;
            default:printf("BYE\n");
                return;
        }
    }
}
void area(int a)
{
    if(a==0){
        printf("Enter Length and Breadth: ");
        scanf("%d %d",&sh.r1.l,&sh.r1.b);
        int ar=sh.r1.l*sh.r1.b;
        printf("%d",ar);
    }
    else if(a==1){
        printf("Enter x and y of Oval: ");
        scanf("%d %d",&sh.o1.x,&sh.o1.y);
        float ar=sh.o1.x*sh.o1.y;
        printf("%.2f",ar*3.14);
    }
}

提前致谢!

最佳答案

作为有风险(非类型安全)的替代方案,并假设该功能是必须要求,请考虑使用 Type-Generic _Generic 宏,它允许您根据类型分派(dispatch)单个调用。

我必须承认,在 10 多年的 C 开发中,我从未遇到过使用此构造的合理情况 - 使用对多态性有适当支持的语言(C++、Java)总是更好。

#define area(shape) _Generic((shape), struct oval: oval_area, struct rect: rect_area)

typedef struct rect{
    int l,b;
}r;
typedef struct oval{
    int x,y;
}o;

int rect_area(struct rect v) {
        return v.l *  v.b ;
}

int oval_area(struct oval v) {
        return v.x * v.y * 2 ;
}

void main(void)
{
        struct rect r ;
        struct oval o ;

        area(r) ;
        area(o) ;
}

关于c - 有没有办法在 C 中巧妙地创建一个函数,使其在不同的参数值中执行不同的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58888312/

相关文章:

c - 无法打印动态分配的指针

C - 如何从c文件中删除与用户输入相同的字符串?

c - 在程序中查看字符串是如何工作的?

c++ - For循环不更新结构对象

c - 在C中查找文件中最长的注释行

c++ - 没有匹配功能 - 专门的签名隐藏通用?

包括来自其他目录的 C++ 不起作用

c# - 带有 SOS 的 Windbg,如何转储 c# 结构

struct - 为什么生命周期强制转换适用于结构而不适用于特征?

c - 从txt文件中读取C中的字符串