【发布时间】:2017-09-26 22:53:24
【问题描述】:
我编写了一个代码,它工作得很好,但只有一行。它给我带来了问题。在上面写着k = Money<double>().increment (k,m); // this should've printed 6.25 的那一行,它根本不起作用。当您将其注释掉并运行代码时……一切正常。出了什么问题,我该如何解决?
感谢您的帮助。
控制台中的错误提示:
main.cpp:59:36: error: 'Money::increment(Money&, Money&)' 没有匹配函数调用错误 main.cpp:59:36:信息:候选人是:
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;
}
【问题讨论】:
-
与问题无关,但我不确定将钱作为
double美元数和double美分数是个好主意。这似乎是两全其美。 -
所以
increment只不过是您已经拥有的东西 -+。我看不出它的目的。做printMoney(a + 5)也很容易,它不会隐藏输出(而且FWIW,有一个标准的std::put_money来格式化货币,所以即使printMoney也是不必要的)。您还需要一个Money对象才能使用increment,尽管您甚至没有使用该对象。
标签: c++ function templates operators