简体   繁体   中英

Default value in struct field when instance it

I've just started to learn C++.

I have this struct :

struct dateTime
{
    int sec;
    int min;
    int hour;
    int day;
    int mon;
    int year;
    bool daylightSaving;
    char timeZone;
};

And I need to set daylightSaving to false by default.

How can I do it? Maybe I have to use a class instead of a struct .

You can write for example

struct dateTime
{
    int sec;
    int min;
    int hour;
    int day;
    int mon;
    int year;
    bool daylightSaving = false;
    char timeZone;
};

So you say in C++, what about having a default constructor initializing all values?

struct dateTime
{
 dateTime()
 : sec(0)
 , min(0)
 , hour(0)
 , day(0)
 , mon(0)
 , year(0)
 , daylightSaving(false)
 , timeZone('a') //Are you sure you just want one character? time zones have multiple... UTC GMT ...
 {}

...
}

You can use a class instead, but the difference is only that all values are private by default. So you need

class ...
{
   public:
   ...
}

to have the same behavior as with the struct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM