c++ 构造函数初始化表列

1. 标准构造函数

class IntCell{
public:
    IntCell(){
        storedValue = 0;
    }
    IntCell(int initialValue){
        storedValue = initialValue;
    }
    int read(){
        return storedValue;
    }
    void write(int x){
        storedValue = x;
    }

private:
    int storedValue;
};

跟java很相似。

2. 初始化表列

class IntCell{
public:
    IntCell(int initialValue=0):storedValue {initialValue} {}
    int read() const{
        return storedValue;
    }
    void write(int x){
        storedValue = x;
    }
private:
    int storedValue;
};

在函数体前使用了初始化表列(initializtion list),直接将数据成员初始化了。

// c++11
:storedValue{ initialValue}{}
// 老的写法
:storedValue (initialValue){}

3. 举个例子

二叉树的定义,用初始化表列来定义很明显的要短很多

struct TreeNode2 {
         int val;
         TreeNode2 *left;
         TreeNode2 *right;
         TreeNode2(int x) : val{x}, left{NULL}, right{NULL} {}
};
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main(){
    TreeNode t1{1};
    cout<<t1.val<<endl;
    TreeNode2 t2{2};
    cout<<t2.val<<endl;

    return 0;
}

TreeNode用的c++11的语法。这语法还是挺实用的。

posted @ 2021-02-06 17:34  过去的我  阅读(153)  评论(0编辑  收藏  举报