首页 > 解决方案 > 在重载的构造函数中调用程序员定义的构造函数

问题描述

我试图在重载的 3 参数构造函数中调用程序员定义的默认构造函数。当我创建我的 Date 类的实例时,我传递了 3 个参数,然后重载的构造函数将这些参数传递给验证函数。如果返回值为 false,我想在重载的构造函数中调用我的默认构造函数,但我得到了垃圾值。 1/-858993460/-858993460 在构造函数中调用构造函数可以吗?

//test.cpp

int main ()
{
    date d1(m, d, y);
}

//header
class Date {
private:
    string month;
    int day, year;
    bool validateDate(string, int, int);
    //Date();
public:
    Date();
    Date(string, int, int);
    void print(DateFormat type);
};

//implmentation
Date::Date() : month("January"), day(1), year(2001) { cout << "INSIDE CONST" << endl; } //default constructor

Date::Date(string m, int d, int y)  //overloaded constructor
{
    if (!validateDate(m, d, y))
    {
        cout << "IF FALSE" << endl;
        //Date(); //This doesn't work
        Date d1;  //This doesn't work as well
    }
    else
    {
        month = m;
        day = d;
        year = y;
        cout << "MONTH IS :" << month << " DAY IS: " << day << " YEAR IS: " << year << endl;
    }
}

标签: c++

解决方案


推荐阅读