2016年9月21日 星期三

用function call operator 來作getter 和 setter

我的結論是目前不推薦使用.

code 如----以下所示

網上有人大推這種 get/set 方法. 認為其不用 .getxxx() , .setxxx(...)
或許小程式有其優雅,

缺點是無法簡單的用 regular/expression 來搜尋其get/set 的引用.
但是一個 regular/expression 無法搜尋引用的寫法,表示人在閱讀,推敲其 code 時,
也要增加額外的負擔, 記住 (以下的code為例) class 產生出來的 instance 名子,才能追其code.

.要靠 compiler 級別的editor 才能找出其引用.
-------------------------------
class cInt {
    int v;
public:
    cInt() : v(0) {}

    int operator ()()                // cInt value get-function
    {
        return v;
    }

    void operator ()(int new_v)        // cInt value set-funciton
    {
        v = new_v;
    }

    void dump(){
        Output("cInt'v=%d\n",v);
    }
};

void test_paren_operator()
{
    cInt ci;
    ci.dump();
    // int v1=ci.v;    // not public
    int v2=ci();    // get

    ci(3);            // set
    ci.dump();
    // ci() = 4;    // not l-value
    ci.dump();
}
--------------

cInt'v=0
cInt'v=3
cInt'v=3

標籤: , , ,

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁