编写函数时,我必须声明输入和输出数据类型,如下所示:
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)