溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++11類內初始化怎么實現(xiàn)

發(fā)布時間:2021-11-26 14:33:45 來源:億速云 閱讀:151 作者:iii 欄目:大數(shù)據

本篇內容主要講解“C++11類內初始化怎么實現(xiàn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C++11類內初始化怎么實現(xiàn)”吧!

重復的初始化代碼

考察下面的代碼:

enum LineStyle{

   lsSolid,

   lsDash,

   lsDot,   

};

class Rect

{

public:

   Rect()

       :left{0}, top{0}, right{0}, bottom{}

       ,style{lsSolid}

   {    

    }

   Rect(int l, int t, int r, int b)

       :left{l}, top{t}, right{r}, bottom

       ,style{lsSolid}

   {

   }

   Rect(int l, int t, int r, int b, LineStyle ls)

       :left{l}, top{t}, right{r}, bottom

       ,style{ls}

   {

   }

private:

   int top;

   int left;

   int right;

   int bottom;

   LineStyle style;   

};

這算是正常不過的代碼,但是有一個不算是問題的問題:初期值為缺省值的數(shù)據包成員也需要在構造函數(shù)里指定,感覺不好。

類內初始化

C++11中引入了類內初始化器,以減少構造函數(shù)和初始化代碼的數(shù)量。說起來挺玄,其實就是下面代碼中背景加亮的部分。

class Rect

{

public:

   Rect(int l, int t, int r, int b)

       :left{l}, top{t}, right{r}, bottom

   {  

   }

   Rect(int l, int t, int r, int b, LineStyle ls)

       :left{l}, top{t}, right{r}, bottom

       ,style{ls}

   {

   }

private:

   int top{0};

   int left{0};

   int right{0};

   int bottom{0};

   LineStyle style{lsSolid};   

};

類內初始化之后,構造函數(shù)只需要負責和缺省值不同的部分就好,代碼精煉很多了。

到此,相信大家對“C++11類內初始化怎么實現(xiàn)”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI