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

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

概述编写函数我必须声明输入和输出数据类型,如下所示: int my_function (int argument) {} 是否可以做出这样一个声明,我的函数会接受类型为int,bool或char的变量,并可以输出这些数据类型? //non working example[int bool char] my_function ([int bool char] argument) {} 你的选择是 替代 编写函数我必须声明输入和输出数据类型,如下所示:
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();}
总结

以上是内存溢出为你收集整理的c – 是否可以产生接受给定参数的多种数据类型的函数?全部内容,希望文章能够帮你解决c – 是否可以产生接受给定参数的多种数据类型的函数?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1254655.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存