我不知道这个问题是否已经在stackoverflow上回答了.但是我根本无法找到正确的关键字进行搜索.
我在下面插入了一些我的代码的下载版本.
所以基本上我在main()中要做的是从t2中减去122.我想我的编译器会自动将整数转换成一个Timestamp对象,然后按照’Timestamp.cpp’所示的方式减去它.
但是当它到达t4它不会转换它,给我以下错误:
no match for ‘operator-‘ in ‘722 – t1’
我100%肯定这是可能的.但是怎么样
也许我完全错了转换…所以请尽快纠正我,我正在尝试学习一些东西.
剥离代码:
main.cpp中:
#include <iostream> #include <iomanip> #include "Timestamp.h" using namespace std; int main() { Timestamp t3(t2 - 122); cout << "T3 = " << t3 << endl; Timestamp t4(722 - t1); cout << "T4 = " << t4 << endl; return 0; }
Timestamp.h
#ifndef TIJDSDUUR_H #define TIJDSDUUR_H using namespace std; class Timestamp { public: Timestamp(int); Timestamp operator- (const Timestamp &t); private: int hour; int min; };
Timestamp.cpp
Timestamp::Timestamp(int m) : hour(0),min(m) { } Timestamp Timestamp::operator- (const Timestamp &t) { Timestamp temp; temp.hour = hour; temp.min = min; temp.hour -= t.hour; temp.min -= t.min; while(temp.min < 0.00) { temp.hour--; temp.min += 60; } return temp; }
解决方法
与其他答案提出的相反,您不需要提供一个专门的运算符 – 它采用int和Timestamp,而是可以(也可能应该)使operator成为一个非成员函数:
Timestamp operator-( Timestamp lhs,Timestamp const & rhs ); // Returns a timestamp?? really??
这样编译器可以自由地将转换应用于左侧和右侧的操作数,并使用从int到Timestamp的隐式转换.
您可以阅读关于运算符重载here的设计和实现的简短说明,也可以在SO中的[C-faq]标签中搜索“运算符超载”.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。