模板,没有匹配函数来调用错误

Tuğ*_*man 2 c++ templates function operators

我已经制作了一个很好但只有一行的代码.这给我带来了麻烦.在它说它k = Money<double>().increment (k,m); // this should've printed 6.25不起作用的线上.当你评论它并运行代码......一切正常.怎么了,怎么解决?

谢谢您的帮助.

控制台中的错误说:

main.cpp:59:36:错误:'Money :: increment(Money&,Money&)'没有用于调用错误main.cpp的匹配函数:59:36:info:candidate is:
main.cpp:41:3:info :T Money :: increment(T,T)[with T = double]
main.cpp:41:3:info:参数1从'Money'到'double'没有已知的转换

好吧......候选人也是空的.正如我所说,没有那条线,一切都很完美.

这是代码:

#include <iostream>
using namespace std;

template <class T>
class Money {
  private:
    T dollar, cent;
  public:
    Money(T a, T b){
        dollar = a;
        cent = b;
    }

  Money(){
    dollar = 0;
    cent = 1;
  }

  Money& operator +=(const Money& v){
    dollar += v.dollar;
    cent += v.cent;
    return (*this);
  }

  Money operator +(const Money& v) const{
    Money temp(*this);
    temp += v;
    return temp;
  }

  Money& operator =(const Money& v){
    dollar = v.dollar;
    cent = v.cent;
    return (*this);
  }

  T increment(T value, T amount);
};

template <class T>
T Money<T>::increment(T value, T amount)
{
  T result = 0;
  result += value + amount;
  cout << result << " $" << endl;
  return result;
}

int main()
{
  int a = 2;
  double b = 3.45;

  Money<double> k(3,75);
  Money<double> m(2,50);

  a = Money<double>().increment (a,5); // this prints 7
  b = Money<double>().increment (b,4.5); // this prints 7.95
  k = Money<double>().increment (k,m); // this should've printed 6.25
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 5

T在的情况下Money<double>就是double,但你不及格doubles到Money<double>::increment(),你逝去的Money<double>情况下,有从没有隐式转换Money<double>到double.

有几种方法可以解决这个问题.

  • 您可以创建转换运算符Money<T>::operator T() const;.这将提供一个隐式转换来自Money<double>于double,你可以定义它做什么.编译器将在Money<double>您传递的两个实例上自动调用此运算符.
  • 你可以添加一个重载Money<T>::increment(Money const &, Money const &);.
  • 你可以Money<T>::increment成为一个模板功能.

从您的代码中不清楚您应该采用哪种方法,但其中一种方法将解决此特定错误.