93 可读性
 将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

Overload a C++ function according to the return value
根据返回值重载 C++ 函数

134 1

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)

You can assume the first parameter is between 0 -9, no need to verify the input or have any error handling.

时间:原作者:0个回答

67 5
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;
};

Not that i would use that.

原作者:
...