0
我有我的老师告诉我们在.h文件中使用这个方法的任务:重载字符串()操作
operator string();
以任何方式,我们不能偏离它。
所以在我的.cpp文件我有:
Currency::operator string(){
stringstream output;
output<<"$";
output<<dollars;//Why does this return garbage for money1+money2??
output<<".";
output<<cents;
string outputstring = output.str();
return outputstring;
}
但是当我做string(money1+money2)
返回垃圾,它工作正常时,我只是做“字符串(MONEY1)`。我想知道我做错了什么。
任何帮助将是伟大的。
这里是我的重载+操作员代码:
Currency& Currency::operator+(const Currency &rhs){
Currency temp;
temp.dollars = dollars + rhs.dollars;
temp.cents = cents + rhs.cents;
temp.simplify();
return temp;
}
注:我已运行调试,并有一个与重载+操作没有问题;它返回它应该的。
你的错误可能在于你的'运营商+',而不是在'运营商string'。 –
您的问题可能出现在您*未显示给我们的代码中。请在这里创建一个最小的**完整的**示例程序并复制粘贴。在这个过程中,你可能会发现自己的错误。请参阅http://sscce.org获取更多信息。 –
仅仅因为'operator +'*出现*返回期望值并不意味着它*正确*。尤其是使用C++。 –