c++ - 复制构造函数参数为 0
问题描述
我减去两个 Date 对象,并在我重载的减号运算符中返回我创建的另一个 Date 类的实例。但是由于某种原因,在重载的减号函数完成并从初始化调用复制构造函数后,参数为0。这是为什么。
//日期.h
class Date
{
int month, day, year;
Date *datePtr = this;
public:
Date();
Date(Date &);
bool operator==(const Date& obj);
bool operator>(const Date& obj);
Date operator-(const Date& obj);
Date operator=(const Date& obj);
friend istream &operator>>(istream& in, Date &obj);
friend ostream &operator<<(ostream& out, Date &obj);
};
//test.cpp
cout << "Date 2 is later in time than Date 1 by \n";
Date temp = date2 - date1; //Overloaded minus called then Copy Constructor from initialization
cout << temp << endl;
//日期执行
Date Date::operator-(const Date& obj)
{
Date tempDate = *this;
if (tempDate.datePtr->day >= obj.day)
{
tempDate.datePtr->day = tempDate.datePtr->day - obj.day;
}
else
{
tempDate.datePtr->day = tempDate.datePtr->day + 30;
tempDate.datePtr->day = tempDate.datePtr->day - obj.day;
}
if (tempDate.datePtr->month > 1)
{
tempDate.datePtr->month = tempDate.datePtr->month - 1;
}
else
{
tempDate.datePtr->month = 12;
tempDate.datePtr->year = tempDate.datePtr->year - 1;
}
if (tempDate.datePtr->month >= obj.month)
{
tempDate.datePtr->month = tempDate.datePtr->month - obj.month;
}
else
{
tempDate.datePtr->month = tempDate.datePtr->month + 12;
tempDate.datePtr->month = tempDate.datePtr->month - obj.month;
tempDate.datePtr->year = tempDate.datePtr->year - 1;
}
tempDate.datePtr->year = tempDate.datePtr->year - obj.year;
return tempDate;
}
//复制构造函数
Date::Date(Date &obj)
{ /*obj.month, day and year is 0 here but should be the value from return Date instance from overloaded minus function.*/
cout << "INSIDE COPY CONSTRUCTOR" << obj.month << "/" << obj.day << endl;
datePtr = new Date;
(*datePtr).month = obj.month;
(*datePtr).day = obj.day;
(*datePtr).year = obj.year;
}
解决方案
您需要将 datePtr 对象实际保存到复制构造函数中的当前对象。您确实为 datePtr 设置了月/日/年,但这不会影响对象的当前实例。这是因为(在您的头文件中),尽管您设置了 datePtr = this,但这并不意味着 datePtr就是这个。它只是指向 this 的地址(或者换句话说,当前实例化)。调用 datePtr = new Date; 只是更改 datePtr 指向的位置,而不是它指向的数据。将您的复制构造函数更改为以下内容:
Date::Date(const Date &obj)
{
this->month = obj.month;
this->year = obj.year;
this->day = obj.day;
}
正如评论中的某个人指出的那样,成员初始化列表也是一种方法。为什么要使用它们有很多原因,阅读它的好地方在这里:https ://www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c /
如果您想查看它,这就是使用成员初始化列表的代码的外观:
Date::Date(const Date &obj) : month(obj.month), year(obj.year), day(obj.day)
{
// Nothing <3
}
推荐阅读
- sql - 如何分离 IP '103.151.184.6' 并在 SQL 中存储为单独的值
- javascript - 使用 axios 响应发布请求无法正常工作
- tic-tac-toe - 是否可以暴力破解这个 5*5 井字游戏?
- swift - 为 forEach 循环中的每个项目生成随机背景颜色
- go - 使用 go-cmdtest 进行命令测试
- react-native - 在 react-native-calendar-picker 上禁用星期日
- flutter - 如何在flutter中将Either Right初始化为空值
- javascript - 如何检查 window.locaton 是否在 Chrome 控制台中使用 JavaScript 成功加载?
- momentjs - 如果超过 6 小时,我如何获得默认日期?
- kubernetes - 如何从无头服务获取 pod 主机名列表?