Вопрос

I have a class Date. let date be:

class Date
{
private:
    unsigned int _day;
    unsigned int _month;
    unsigned int _year;
public:
    const unsigned int& Day;
    const unsigned int& Month;
    const unsigned int& Year;

    Date() : Day(_day), Month(_month), Year(_year)
    {  }
}

For some reason, after the constructor is called Day, Month and Year do not point/refer to _day, _month and _year.

One guess of mine would be that they are being set before memory is allocated to the class, how would i go about solving this issue (aka setting the references after memory allocation)?

Thanks in advance!

EDIT: More info

The value of _day (for eg) is not returned when i get the value of Day. I get a seemingly random number.

Это было полезно?

Решение

It's not very clear what you want to achieve. In your Date class you can access _date, _month, _year directly why do you want to set another reference?

But to answer you question

The value of _day (for eg) is not returned when i get the value of Day. I get a seemingly random number

Actually, the values are being returned, but you are getting garbage because _day, _month, and _year are just uninitialized integers. You need to initialize them in the initializer list first:

Date() : _day(0), _month(1), _year(2), Day(_day), Month(_month), Year(_year)

Другие советы

You should expose them using getters returning const references to avoid having to store them, it is much more convenient.

class Date {
private:
    unsigned int _day;
    unsigned int _month;
    unsigned int _year;

public:
    const unsigned int& Day(){return _day;}
    const unsigned int& Month(){return _month;}
    const unsigned int& Year(){return _year;}
}
Date::Date(unsigned int myDay, unsigned int myMonth, unsigned int myYear)
{
    //Assign values here in constructor.
}

You can write separate methods to return the day, month, or year in the class, or any combination of them for any different date formats that you have planned in the design doc.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top