【发布时间】:2016-11-20 16:27:52
【问题描述】:
我在 C++ 中遇到了一个问题已经好几个小时了,即使在调试器的帮助下,我也无法弄清楚发生了什么。
我正在尝试创建一个Date 类,它(不开玩笑)代表一个日期,包括日、月和年。我还想重载主运算符(++、--、+=、-=、+)。
由于我看不到的原因,一切似乎都正常,除了运算符“+”。
这是我的头文件:
#include <ostream>
class Date {
public:
Date(int year, int month, int day);
~Date();
Date(const Date& date);
Date &operator+(int days);
private:
int m_year;
int m_month;
int m_day;
friend std::ostream &operator<<(std::ostream &os, const Date &date);
};
这是我的 C++ 文件:
#include "Date.h"
using namespace std;
Date::Date(int year, int month, int day)
: m_year(year),
m_month(month),
m_day(day)
{}
Date::~Date() {}
Date::Date(const Date &date)
: m_year(date.m_year),
m_month(date.m_month),
m_day(date.m_day)
{}
ostream &operator<<(ostream &os, const Date &date) {
os << date.m_day << ", " << date.m_month << " " << date.m_year;
return os; <---- debug point A
}
Date &Date::operator+(int days) {
Date newDate(*this);
newDate.m_day = newDate.m_day + days;
return newDate; <---- debug point B
}
还有我的主文件:
#include "Date.h"
#include <ostream>
using namespace std;
int main(int argc, char *argv[])
{
Date date(2013, 12, 12);
cout << date << endl;
cout << date + 2 << endl;
return 0;
}
输出是:
12, 12 2013
1359440472, 12 2013
Process finished with exit code 0
我不明白这个 1359440472 是从哪里来的!!
我试过放调试点(如上图),输出如下:
Debug point A:
date = {const Date &}
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 12
Debug point B:
this = {Date * | 0x7fff5c5ddac0} 0x00007fff5c5ddac0
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 12
days = {int} 2
newDate = {Date}
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 14
Debug point A:
date = {const Date &}
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 1549654616
我无法解释!!最后两个调试检查点之间没有一步,“14”变成了“1549654616”……
这可能是 int 类型的问题(因为它似乎距离 2^24 不远)或运算符 + 的问题,但我不知道如何解决它。
感谢您的帮助, 埃德
【问题讨论】:
-
你通过引用返回一个本地对象,不要那样做。
-
@tkausl:你在 cmets 部分回答;不要那样做。
-
感谢您的回答,这是我第一次遇到按值/引用处理返回的问题(我在learncpp.com/cpp-tutorial/…找到了令人满意的解释)。
-
我只是想强调一个事实:(i)我给出了一个描述性的标题和一个尽可能解释我的问题的描述,(ii)我尝试自己解决它,使用调试器工具和花费时间以及(iii)(最重要的)如果其他人有同样的问题,我确实已经检查过。但是,正如您所看到的,没有什么告诉我这是按值/引用返回的问题,所以我不知道要寻找什么(如果我知道,我就不会问了)。我完全理解我的问题必须被标记为“重复”,但是我看不出降级它的意义。
-
@Edouardb:不要把它当成个人。你的问题很好。只是它是如此基本和普遍,对其他读者没有什么价值,这就是这个地方的真正意义所在。下次你会在提问之前使用正确的学习材料:)
标签: c++ debugging operator-overloading