C++ Primer 筆記——類成員指標

來源:互聯網
上載者:User

標籤:類成員   logs   tor   int   規則   add   資訊   ace   接受   

1.當我們初始化一個成員指標或為成員指標賦值時,該指標並沒有指向任何資料。成員指標指定了成員而非成員所屬的對象,只有當解引用成員指標時,我們才提供對象資訊。

 

2.和普通的函數指標類似,如果成員存在重載的問題,則我們必須顯示地聲明函數類型以明確指出我們想要使用的是哪個函數。和使用指向資料成員的指標一樣,我們使用 .* 或者 ->*運算子作用於指向成員函數的指標。

class test{public:    void Add(int){}    void Add(long){}    void get() {}    };auto pmf = &test::get;    // 使用auto的前提是該函數不接受任何實參void (test::*m_pf)(int) = &test::Add;    // 指向int版本的Addvoid (test::*m_pf1)(int) = test::Add;    // 錯誤,成員函數和指標之間不存在自動轉換規則int main()        {    test t;    (t.*m_pf)(1);    // 注意不要忘了*    return 0;}


 

3.使用類型別名或typedef可以讓成員指標更容易理解。

class test{public:    void Add(int) { }};typedef void (test::*m_pf)(int);m_pf m = &test::Add;using TestAdd = void (test::*)(int);TestAdd m_testadd = &test::Add;int main()        {    test t;    (t.*m)(1);    (t.*m_testadd)(1);    return 0;}

 

4.從指向成員函數的指標擷取可調用對象的一種方法是使用標準庫模板function。通常情況下,執行成員函數的對象將被傳給隱式的this形參。

std::vector<std::string> vec = {"test"};std::function<bool(const std::string&)> fp = &std::string::empty;bool b = fp(*vec.begin());            // 可以理解為 (*vec.begin()).*fp();

 

5.mem_fn可以從成員指標產生一個可調用對象,和function不同的是,mem_fn可以根據成員指標的類型推斷可調用對象的類型,而無須使用者顯示地指定。

std::vector<std::string> vec = {"test"};bool b = std::mem_fn(&std::string::empty)(*vec.begin());        // 正確,使用 .* 調用對象    b = std::mem_fn(&std::string::empty)(vec.begin());                // 正確,使用 ->* 調用對象    


6.我們還可以使用binf從成員函數產生一個可調用對象,和function類似的地方是,必須將函數中用於表示執行對象的隱式形參轉換成顯示的。和mem_fn類似的是,bind產生的可調用對象的第一個實參既可以是指標也可以是引用。

std::vector<std::string> vec = {"test"};bool b = std::bind(&std::string::empty, std::placeholders::_1)(*vec.begin());        // 正確b = std::bind(&std::string::empty, std::placeholders::_1)(vec.begin());                // 正確

 

C++ Primer 筆記——類成員指標

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.