rsk*_*k82 20 c++ variables types function
编写函数我必须声明输入和输出数据类型,如下所示:
int my_function (int argument) {}
Run Code Online (Sandbox Code Playgroud)
有可能做出这样的声明,我的函数会接受int,bool或char类型的变量,并且可以输出这些数据类型吗?
//non working example
[int bool char] my_function ([int bool char] argument) {}
Run Code Online (Sandbox Code Playgroud)
par*_*mar 28
你的选择是
替代方案1
您可以使用模板
template <typename T>
T myfunction( T t )
{
return t + t;
}
Run Code Online (Sandbox Code Playgroud)
替代方案2
普通函数重载
bool myfunction(bool b )
{
}
int myfunction(int i )
{
}
Run Code Online (Sandbox Code Playgroud)
您为所期望的每个参数的每种类型提供不同的函数.您可以混合使用备选方案1.编译器将适合您.
替代3
你可以使用union
union myunion
{
int i;
char c;
bool b;
};
myunion my_function( myunion u )
{
}
Run Code Online (Sandbox Code Playgroud)
替代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();
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
template <typename T>
T f(T arg)
{
return arg;
}
int main()
{
std::cout << f(33) << std::endl;
std::cout << f('a') << std::endl;
std::cout << f(true) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
33
a
1
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
int i = f(33);
char c = f('a');
bool b = f(true);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28515 次 |
最近记录: |