复制构造函数参数为0

Copy constructor parameter is 0

我正在减去两个 Date 对象,在我的重载减号运算符中,我 return 我创建了另一个 Date class 的实例。但是由于某些原因,重载的minus函数完成后,从初始化调用复制构造函数后,参数为0。这是为什么。

//Date.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 设置了 month/day/year,但这不会影响对象的当前实例。这是因为(在您的头文件中),尽管您设置了 datePtr = this,但这并不意味着 datePtr is this。它只是指向 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
}