运算符重载模板

use*_*004 0 c++ templates operator-overloading

我试图使用operator <,>方法运行一个带有模板的程序,我得到一个编译器错误告诉我"从这里实例化"并且不能转换为Temps<double>' to双重',当我调用运算符函数时问题开始了代码..

    template <class T>
class Temps
{   
 private:   
 T a;

 public:
 Temps()
 {
 }
 Temps(T b)
 {
   a=b;
         }     
 T operator<(Temps c)
 {
   if (a < c.a)
   {
      return *this;
   }
   return c;        
 } 
 T operator>(Temps c)              
   {
      if (a > c.a)
      {
         return *this;
      }

      return c;                 
   }   

};

int main()
{

    double d1 = -9.002515,d2=98.321,d3=1.024;

    Temps<double>mag(d1);
    Temps<double>lag(d3);
    Temps<double>tag;
    tag=mag < lag;

    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

drd*_*cox 6

你的<>函数返回a T,但你试图返回一个Temps<T>.您可能想要返回的是a或者c.a.但是,正常的语义<>是返回一个bool,所以你可能需要返回a < c.a<:

bool operator <(Temps c) { return a < c.a; }
Run Code Online (Sandbox Code Playgroud)

类似的>.