先说明具体问题
Time aida(3, 35);
Time temp;
temp = aida*1.17;
cout << "Aida * 1.17 = " << temp << endl;
cout << aida*10.0 << endl;
最后一行的“<<”出现了题目的错误,但是倒数第二行是正常输出的,下面是头文件和源代码
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int min);
friend Time operator*(Time &a, double n);
friend ostream & operator<<(ostream &os, Time &a);
};
Time operator*(Time &a, double n)
{
Time temp;
long total = a.hours * 60 * n + a.minutes * n;
temp.hours = total / 60;
temp.minutes = total % 60;
return temp;
}
ostream & operator<<(ostream &os, Time &a)
{
os << a.hours << " hours, " << a.minutes << " minutes.";
return os;
}
刚开始学不是太懂,希望大家指正一下,谢谢。
#include <iostream>
using namespace std;
class Time
{
private:
int hours;
int minutes;
public:
Time() { hours = 0; minutes = 0; }
Time(int h, int min) { hours = h; minutes = min; }
Time& operator*(double n);
friend ostream & operator<<(ostream &os, Time &a);
};
Time& Time::operator*(double n)
{
long total = this->hours * 60 * n + this->minutes * n;
this->hours = total / 60;
this->minutes = total % 60;
return *this;
}
ostream & operator<<(ostream &os, Time &a)
{
os << a.hours << " hours, " << a.minutes << " minutes.";
return os;
}
int main() {
Time aida(3, 35);
Time temp;
temp = aida*1.17;
cout << "Aida * 1.17 = " << temp << endl;
cout << aida*10.0 << endl;
return 0;
}
Aida * 1.17 = 4 hours, 11 minutes.
41 hours, 50 minutes.
另外,建议你用英文原版的编译器。什么二进制,是Binary,在这里翻译成二元(运算符)。