首页 > 解决方案 > 使用结构作为函数参数的函数重载

问题描述

我可以使用结构作为参数的函数重载吗?如果是,我该如何实施?这种方式行得通吗?

void function1(struct_a *a, struct_b *b, int i)
{
    cout << "abc";
}

void function1(struct_c *c, struct_d *d)
{
    cout << "def";
}

int main()
{
    struct_a *a = (struct_a *)<some-data-a>;
    struct_b *b = (struct_b *)<some-data-b>;
    struct_c *c = (struct_c *)<some-data-c>;
    struct_d *d = (struct_d *)<some-data-d>;

    function1(a, b, 1);
    return 0;
}

标签: c++

解决方案


是的你可以。您可以重载任何函数,具体取决于:1)参数数量 2)参数的数据类型

结构是用户定义的数据类型,因此您可以通过各种方式使用它们来区分不同的重载函数并将它们与原始数据类型混合。

在您的情况下,您可以通过以下方式调用第一个函数(带有 3 个参数):

function1(a, b, 1);

对于使用第二个函数(带有 2 个参数),您只需提供 struct_c 和 struct_d 的 2 个参数:

function1(c, d);

推荐阅读