我在这里读到了几个关于这个主题的问题,这个问题似乎让我感到困惑.我刚刚开始学习C++,我还没有学过模板或运算符重载等等.
现在有一种简单的重载方式
class My {
public:
int get(int);
char get(int);
}
Run Code Online (Sandbox Code Playgroud)
没有模板或奇怪的行为?或者我应该
class My {
public:
int get_int(int);
char get_char(int);
}
Run Code Online (Sandbox Code Playgroud)
?
我们都知道你可以根据参数重载一个函数:
int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); }
Run Code Online (Sandbox Code Playgroud)
你能根据返回值重载一个函数吗?根据返回值的使用方式定义一个返回不同内容的函数:
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)
Run Code Online (Sandbox Code Playgroud)
您可以假设第一个参数介于0-9之间,无需验证输入或进行任何错误处理.