首页 > 解决方案 > 复制构造函数参数为 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;
}

标签: c++copy-constructor

解决方案


您需要将 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
}

推荐阅读