gpt4 book ai didi

C++ 运算符问题

转载 作者:可可西里 更新时间:2023-11-01 16:29:58 25 4
gpt4 key购买 nike

我不知道这个问题是否已经在 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;
}

时间戳.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;
};

时间戳.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;
}

最佳答案

与其他答案的建议相反,您不需要提供采用 intTimestamp 的专用 operator-,相反,您可以(并且可能应该)将 operator- 设为非成员函数:

Timestamp operator-( Timestamp lhs, Timestamp const & rhs ); // Returns a timestamp?? really??

这样编译器就可以自由地将转换应用于左侧和右侧操作数,并使用从 intTimestamp 的隐式转换。

您可以阅读有关运算符重载的设计和实现的简短说明 here ,或者您可以在 SO 中的 [C++-faq] 标记中搜索“运算符重载”。

关于C++ 运算符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7585686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com