构建一个保存日期的构造函数

我试图构建一个包含变量的构造函数,并在主函数中调用构造函数,以便我可以使用此构造函数执行日期,如您所见

class Date
{
    int day;
    int month;
    int year;
public:
    Date(int d, int m, int y) {
        d = day;
        m = month;
        y = year;
    }
public:
    void print()
    {
        cout << "The Day is : " << day << endl;
        cout << "The Month is : " << month << endl;
        cout << "The Year is : " << year << endl;
    }
};

int main()
{
    Date birth(4, 4, 2004);
    birth.print();
}

问题是我得到的值与我认为应该是的输出值不同:

The Day is : 4
The Month is : 4 
The Year is : 2004 

但我得到了这个:

The Day is : -858993460    
The Month is : -858993460    
The Year is : -858993460    

我认为这是内存地址或类似的东西,但为什么我得到它而不是我想要的值?

回答

你在错误的方向上做任务。形象化的方法是:

target = source;

所以写构造函数的正确方法是:

Date(int d, int m, int y) {
    day = d;
    month = m;
    year = y;
}


以上是构建一个保存日期的构造函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>