根据返回值重载一个C++函数 [英] Overload a C++ function according to the return value

查看:39
本文介绍了根据返回值重载一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆