我正在寻找一种切换函数重载的方法,我通过int成员变量的值调用类。等。
class someclass
{
private:
int tag;
SomeArithmeticType val;
// some class members
public:
void setvalue (int I){val = I; tag = 0}
void setvalue (float f) {val = f; tag = 1}
void setvalue(other o){val =o; tag=2}
int method(){}
float method(){}
other method(){}
// rest of class
}
main
{
// stuff
some class s;
s.setvalue(9.7654);
cout << s << endl;
}
如果tag是0我想使用Int版本的方法但是如果它是另一个数字我想要方法的相应重载。
答案 0 :(得分:1)
您不能在同一个函数中使用不同的返回类型。通过在每个定义中使用不同的参数列表,可以重载函数名称。我建议使用不同的函数名来获得不同的返回类型。
答案 1 :(得分:1)
你不想在这里超载,你想要一个模板化的类:
template <typename T = int> /* defaulting to int */
class SomeClass
{
private:
T tag;
public:
T method();
};
你不能重载函数返回类型,它必须是相同的返回类型,但参数可以不同。