加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:18:33 所属栏目:百科 来源:网络整理
导读:编写函数我必须声明输入和输出数据类型,如下所示: int my_function (int argument) {} 是否可以做出这样一个声明,我的函数会接受类型为int,bool或char的变量,并可以输出这些数据类型? //non working example[int bool char] my_function ([int bool char]
编写函数我必须声明输入和输出数据类型,如下所示:
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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读