微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 是否可以产生接受给定参数的多种数据类型的函数?

编写函数我必须声明输入和输出数据类型,如下所示:
int my_function (int argument) {}

是否可以做出这样一个声明,我的函数会接受类型为int,bool或char的变量,并可以输出这些数据类型?

//non working example
[int bool char] my_function ([int bool char] argument) {}

解决方法

你的选择是

替代1

你可以使用模板

template <typename T> 
T myfunction( T t )
{
    return t + t;
}

替代2

普通功能超载

bool myfunction(bool b )
{
}

int myfunction(int i )
{
}

您为每种类型的每个参数提供一个不同的功能.你可以混合备选方案1.编译器将适合您.

替代3

你可以使用联合

union myunion
{ 
    int i;
    char c;
    bool b;
};

myunion my_function( myunion u ) 
{
}

替代4

你可以使用多态.可能是int,char,bool的过分,但对于更复杂的类类型可能有用.

class BaseType
{
public:
    virtual BaseType*  myfunction() = 0;
    virtual ~BaseType() {}
};

class IntType : public BaseType
{
    int X;
    BaseType*  myfunction();
};

class BoolType  : public BaseType
{
    bool b;
    BaseType*  myfunction();
};

class CharType : public BaseType
{
    char c;
    BaseType*  myfunction();
};

BaseType*  myfunction(BaseType* b)
{
    //will do the right thing based on the type of b
    return b->myfunction();
}

原文地址:https://www.jb51.cc/c/111904.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐