构造函数对数据成员进行初始化的方法

来源:互联网 发布:socket网络通信流程 编辑:程序博客网 时间:2024/04/29 18:39

1.常规方法:

假设定义了如下类:

class TableTennisPlayer{    private:        string firstName;        string lastName;        bool hasTable; //该球员是否有球桌    public:        TableTennisPlayer(string & fn, string & ln, bool ht = true);        void name() const;        bool hasTable() const;        void resetTable(bool b);}
则实现这个类的构造函数的常规方法如下:

TableTennisPlayer::TableTennisPlayer(string & fn, string & ln, bool ht){    firstName = fn;    lastName = ln;    hasTable = ht;}
2.也可以使用如下方法:

TableTennisPlayer::TableTennisPlayer(string & fn, string & ln, bool ht) :firstName(fn), lastName(ln), hasTable(ht) {}
3.当类的数据成员中有const int Size;这种const修饰的数据成员时,必须使用上面的第二种方法,如下例:

假设有如下Queue类:

class Queue{    private:        int currentNum;   //队列的当前人数        const int historyNum;  //队列的历史上所有的人数之和    public:        Queue(int cn, int hn);};
因为historyNum是const类型,所以只能用如下方式写构造函数:

Queue::Queue(int cn, int hn) :historyNum(hn){    currentNum = cn;}
而currentNum没用const修饰,所以可以用上述的两种方法中的任何一种都行,即如下方式也行:

Queue::Queue(int cn, int hn) : historyNum(hn), currentNum(cn) {}




0 0
原创粉丝点击