如何在c++中的重载函数之间切换

how do I switch between overload functions in c++

本文关键字:函数 之间 重载 c++      更新时间:2023-10-16

我正在寻找一种方法来切换我通过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;
}

如果标签是0,我想使用Int版本的方法,但如果它是另一个数字,我想要相应的方法重载

同一个函数不能有不同的返回类型。可以通过在每个定义中使用不同的形参列表来重载函数名。我建议使用不同的函数名来获得不同的返回类型。

你不想在这里重载,你想要一个模板化的类:

template <typename T = int>  /* defaulting to int  */
class SomeClass
{
      private:
         T tag;
      public:
         T method();
};

不能重载函数的返回类型,必须是相同的返回类型,但参数可以不同