为什么更多主流的静态类型语言不支持返回类型的函数/方法重载?我想不出那样做.通过参数类型支持过载似乎没有那么有用或合理.怎么这么不受欢迎呢?
programming-languages overloading language-design function-calls
我们都知道你可以根据参数重载一个函数:
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之间,无需验证输入或进行任何错误处理.
为什么c ++类不能为函数和数据成员使用相同的名称?
class demo{
public:
int size();
private:
int size;
};
int main(){
return 0;
}
C:\Users\S>g++ demo.c
demo.c:5:7: error: declaration of 'int demo::size'
demo.c:3:7: error: conflicts with previous declaration 'int demo::size()'
Run Code Online (Sandbox Code Playgroud) 可能重复:
返回类型的函数重载?
嗨,
在重载时我们说参数列表必须按数字或类型不同,但在返回类型上无关紧要,为什么这样呢?
功能
//Function 1
int Add(int a, int b)
{return a+b;}
//Function 2
Double Add(Double a, Double b)
{return a+b;}
//Function 3
Double Add(int a, int b)
{return (Double)a+b;}
Run Code Online (Sandbox Code Playgroud)
函数1 2是重载的,其中函数1和3不是??? 原因???
任何帮助都非常感谢.