简体   繁体   中英

What is the use of a private init() member function?

EDIT for more details: this is a school assignment and the private variables/functions of the Time class were given to me already. I have to declare and define a member function which adds two Times together and saves the result in the Time member variable of another class. I'm not sure what the assignment intends me to do with the given init() function.

Say I have a class Time:


class Time {

    public:

        Time();

        Time(int hours, int mins, int secs);
        
        // public member functions here
        
        friend std::ostream& operator << (std::ostream&, Time&);


    private:

        int theHour;
        int theMins;
        int theSecs;    
        
        void init(int hours, int minutes, int seconds);
};

I know one thing I'll have to do when creating a Time object from hours/mins/secs values before setting hours = theHour, mins = theMins, secs = theSecs is check that the values for hours/mins/secs are valid. However, I already have a constructor Time(int hours, int mins, int secs); which I was thinking of defining as follows:

Time::Time(int hours, int mins, int secs)
{ 
     if ((hours < 0) || (mins < 0) || (secs < 0) || (hours > 60) || (mins > 60) || (secs > 60))
     { 
          cout << "Illegal time value.\n";
          exit(1)
     }
     hours = theHour;
     mins = theMins;
     secs = theSecs;
}

If I already have a constructor to initialise an instance of hours, mins, secs as a time object and check for illegal values, what is the point of the void init() function?

This is an old C++ style. It allows multiple constructors to share code.

Modern C++ would use

Time::Time() : Time(0,0,0) { }

which reuses the existing 3-argument ctor.

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