C++ initialization lists for multiple variables

怎甘沉沦 提交于 2019-12-07 01:02:39

问题


I'm trying to learn how to initialize lists.

I have a simple class below and trying to initialize the list of variables. The first Month(int m): month(m) works. I'm trying to do something similar below that line with more than one variable. Is this possible in that format? would I have to break away from the one liner?

class Month
{
public:
    Month(int m) : month(m) {} //this works
    Month(char first, char second, char third) : first(first){} : second(second){} : third(third){} //DOES NOT WORK
    Month();
    void outputMonthNumber(); //void function that takes no parameters
    void outputMonthLetters(); //void function that takes no parameters
private:
    int month;
    char first;
    char second;
    char third;
};

Obviously I don't have much clue how to do this, any guidance would be appreciated, thanks


回答1:


Try this:

  Month(char first, char second, char third) 
     : first(first), second(second), third(third) {} 

[You can do this as a single line. I've split it merely for presentation.]

The empty braces {} are the single body of the constructor, which in this case is empty.




回答2:


Month(char first, char second, char third) 
      : first(first)
      , second(second)
      , third(third)
{} //DOES WORK :)



回答3:


As others have pointed out, it's just a comma seperated list of items. The variable(value) syntax is just a default way of constructing primative datatypes, you can use this method outside of initialization lists for example. In addition, if a member of your class is also a class with a constructor, you'd call it in the exact same way.

You are not only bound to putting the list in the declaration of the class, just for future reference. This code is perfectly fine for example

class Calender{
    public:
         Calender(int month, int day, int year);
    private:
         int currentYear;
         Time time;
};

Calender::Calender(int month, int day, int year) : currentYear(year), time(month, day) {
    // do constructor stuff, or leave empty
};



回答4:


Initializers are comma-separated, and your constructor should have only one body.



来源:https://stackoverflow.com/questions/7603981/c-initialization-lists-for-multiple-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!