我在这里阅读了一些关于这个主题的问题,这似乎让我感到困惑。刚开始学C++,还没有学过模板和运算符重载等。
现在有没有简单的重载方法
class My {
public:
int get(int);
char get(int);
}
没有模板或奇怪的行为?或者我应该只是
class My {
public:
int get_int(int);
char get_char(int);
}
?
最佳答案
不,没有。您不能根据返回类型重载方法。
重载解析考虑到函数签名。函数签名由以下部分组成:
- 函数名称
- cv 限定符
- 参数类型
这是引用:
1.3.11 签名
the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared. [...]
选项:
1) 更改方法名称:
class My {
public:
int getInt(int);
char getChar(int);
};
2) 输出参数:
class My {
public:
void get(int, int&);
void get(int, char&);
}
3) 模板...在这种情况下有点矫枉过正。
关于c++ - 按返回类型重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9568852/