0
Imagine the class DateTime
as follows:
datetime.hpp:
#ifndef DATETIME_HPP
#define DATETIME_HPP
#include <ctime>
class DateTime {
public:
DateTime();
DateTime(int, int, int, int, int);
private:
std::tm *date;
};
#endif // DATETIME_HPP
datetime.cpp:
#include "datetime.hpp"
DateTime::DateTime() : date(new std::tm)
{
//date = new std::tm;
date->tm_sec = 0;
date->tm_min = 0;
date->tm_hour = 0;
date->tm_mday = 0;
date->tm_mon = 0;
date->tm_year = 0;
date->tm_wday = 0;
date->tm_yday = 0;
date->tm_isdst = 0;
date->tm_gmtoff = 0;
date->tm_zone = 0;
}
DateTime::DateTime(int _D, int _M, int _Y, int _h, int _m) : date(new std::tm)
{
date->tm_sec = 0;
date->tm_min = _m;
date->tm_hour = _h;
date->tm_mday = _D;
date->tm_mon = _M;
date->tm_year = _Y-1900;
date->tm_wday = 0;
date->tm_yday = 0;
date->tm_isdst = 0;
date->tm_gmtoff = 0;
date->tm_zone = 0;
}
The above code works as long as I store memory in the constructor list and define the structure fields in the constructor body. I’d like to do everything on the constructor startup list, but I’m really having a hard time figuring it out.
It would be something like:
: date(new std::tm), date{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
and:
: date(new std::tm), date{0, _m, _h, _D, _M, _Y-1900, 0, 0, 0, 0, 0}
Do not construct a hybrid answer of English and Portuguese because it ends up complicating and making the question more confusing to both Portuguese and English speakers. This being the Portuguese community of Stackoverflow the correct is to leave the question only with the Portuguese text. If you want you can also ask the same question in the English version of Stackoverflow with the texts you have in English.
– Isac
Man, I think I understand your question now, but I believe that what you wish to do is not possible. The initialization list is only for initialization of object attributes, and does not serve for "attribute attributes".
– Leonardo Alves Machado
@Leonardoalvesmachado, it is possible, yes, making the initialization aggregated by the operator
new
, thus:date(new std::tm{0, _m, _h, _D, _M, _Y-1900, 0, 0, 0, 0, 0})
.– Mário Feroldi
@Márioferoldi Puts this solution as an answer
– Isac
@Márioferoldi good to know! I had never used this way. Thanks... Put as answer there :)
– Leonardo Alves Machado