【发布时间】:2019-06-22 11:15:45
【问题描述】:
我有一个应用程序可以处理时间数据(小时、分钟、秒)。
在类中添加下一个运算符: - (二元运算符)定义为成员函数:它返回两个操作数之间的差;如果operand1小于operand2,则返回时间0:0:0
只有打印函数和 toseconds() 函数起作用。
这是错误:
Error 2 error C2440: 'type cast' : cannot convert from 'const time' to 'long' 47 1 timeex2
#include <iostream>
using namespace std;
class time {
int hour, min, sec;
void normalize(); // it transforms the sec and min values on the inside of
// [0,59] interval and hour values on the inside of
// [0, 23] interval.
// Ex: the time 25: 79: 80 is transformed in 2 : 20: 20
public:
time(int=0, int=0, int=0); // values of the members are normalized
void print1(); // print on the screen the values as hour : min : sec
void print2(); // print on the screen the values as hour : min : sec a.m. / p.m.
void operator-(const time&);
void toseconds() {
sec=3600*hour+60*min+sec;
cout << sec;
}
// friend time operator+(const time t) {
// time t1, t2, t3;
// t3 = t1 + t2;
// time::normalize();
// return t3;
// }
// friend time operator>(time t1, time t2) {
// toseconds(t1);
// toseconds(t2);
// if (t1 > t2)
// cout << "\nt1 is bigger\n";
// else
// cout << "\nt1 is smaller\n";
// }
// friend time operator==(time t1, time t2) {
// toseconds(t1);
// toseconds(t2);
// if (t1 == t2)
// cout << "\nEqual\n";
// else
// cout << "\nNot equal\n";
// }
};
void time::operator-(const time& t) {
long a = *this; // The error is here
long b = (long)t; // The error is here
if (a < b)
cout << "\n0:0:0\n";
else
cout << "\nThe difference is " << a-b << endl;
}
time::time(int a, int b, int c) {
hour = a;
min = b;
sec = c;
normalize();
}
void time::normalize() {
int s = sec;
int m = min;
int h = hour;
sec = s % 60;
min = (m + s/60) % 60;
hour = (h + m/60 + s/3600) % 24;
}
void time::print1() {
normalize();
cout << hour << ":" << min << ":" << sec << endl;
}
void time::print2() {
normalize();
if (hour >= 13)
cout << hour%12 << ":" << min << ":" << sec << " p.m." << endl;
else
cout << hour << ":" << min << ":" << sec << " a.m." << endl;
}
int main() {
time t1(12,45,30), t2(0,0,54620), t3;
t1.print1();
t2.print1();
t1.print2();
t2.print2();
cout << "\nTime t1 to seconds\n";
t1.toseconds();
t1.operator-(t2);
cin.get();
return 0;
}
【问题讨论】:
-
#include <iostream> using namespace std; class time {组合起来可能不是最好的主意。 -
我认为问题出在运算符上,您正在将类转换为 long,但没有可用的转换。我猜你想打电话给 toSeconds() 或类似的东西。不管 toSeconds 也是错误的。您正在覆盖秒数而不将其他 2 个值设置为 0。该函数很可能应该在不改变对象状态的情况下计算并返回秒数。还是我误解了你想做什么?
-
操作员通常应该返回一个结果——而不是输出 anything 到控制台。
-
@CuriouslyRecurringThoughts 你猜对了,我只想在函数toseconds()中转换成秒,不用修改
-
'我只想在函数toseconds()中转换为秒,不修改'——那么你应该声明函数
const。当然,你需要一个返回值......
标签: c++ class operator-overloading friend-function