根据返回值重载C ++函数 [英] Overload a C++ function according to the return value
本文介绍了根据返回值重载C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们都知道你可以根据参数重载一个函数:
We all know that you can overload a function according to the parameters:
int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); }
可以根据返回值重载函数吗?定义一个函数,它根据如何使用返回值返回不同的东西:
Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:
int n = mul(6, 3); // n = 18
std::string s = mul(6, 3); // s = "666"
// Note that both invocations take the exact same parameters (same types)
您可以假设第一个参数在0-9之间,无需验证输入或有任何错误处理。
You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.
推荐答案
class mul
{
public:
mul(int p1, int p2)
{
param1 = p1;
param2 = p2;
}
operator int ()
{
return param1 * param2;
}
operator std::string ()
{
return std::string(param2, param1 + '0');
}
private:
int param1;
int param2;
};
不是我会用的。
这篇关于根据返回值重载C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文