how to explain return statement within constructor?

后端 未结 6 1564
北海茫月
北海茫月 2020-12-08 23:05

as far as i know , the constructor return nothing , not even void ,

and also

return ;

inside any method means to return void .

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 23:33

    return in a constructor just jumps out of the constructor at the specified point. You might use it if you don't need to fully initialize the class in some circumstances.

    e.g.

    // A real life example
    class MyDate
    {
        // Create a date structure from a day of the year (1..366)
        MyDate(int dayOfTheYear, int year)
        {
            if (dayOfTheYear < 1 || dayOfTheYear > 366)
            {
                mDateValid = false;
                return;
            }
            if (dayOfTheYear == 366 && !isLeapYear(year))
            {
                mDateValid = false;
                return;
            }
            // Continue converting dayOfTheYear to a dd/mm.
            // ...
    

提交回复
热议问题