多个变量的C ++初始化列表 [英] C++ initialization lists for multiple variables
问题描述
我正在尝试学习如何初始化列表。
I'm trying to learn how to initialize lists.
我下面有一个简单的类,试图初始化变量列表。第一个 Month(int m):month(m)
有效。我正在尝试使用多个变量在该行下执行类似的操作。是否可以这种格式?我会不得不摆脱那种班轮吗?
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
推荐答案
尝试一下:
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.
这篇关于多个变量的C ++初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!