Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 類成員函式指標的三個要點:宣告、->* 與 .*

成員函式指標的語法一向讓人頭痛,但只要抓住三個固定動作,就不容易出錯:

一、宣告時用 ::*;
二、透過物件指標呼叫時用 ->*;
三、透過物件本身呼叫時用 .*。

完整範例

/** 定義基類和子類 **/
class Base {
public:
    virtual void print1() {
        std::cout << "Base::print1()" << std::endl;
    }

    virtual void print2() {
        std::cout << "Base::print2()" << std::endl;
    }
};

class Derived : public Base {
public:
    virtual void print1() {
        std::cout << "Derived::print1()" << std::endl;
    }

    virtual void print2() {
        std::cout << "Derived::print2()" << std::endl;
    }
};

/** 申明類成員函式指針類型 **/
typedef void (Base::*fn)();

/** 通過對象指針調用類函數指針 **/
void test1(Base* obj, fn func) {
    (obj->*func)();
}

/** 通過對象調用類函數指針 **/
void test2(Base& obj, fn func) {
    (obj.*func)();
}

void test_function_pointer() {
    Base b;
    Derived d;

    test1(&b, &Base::print1);
    test1(&b, &Base::print2);
    test1(&d, &Base::print1);
    test1(&d, &Base::print2);

    test2(b, &Base::print2);
    test2(d, &Base::print2);
}

幾個容易忽略的細節

外層括號不能省。 (obj->*func)() 一定要那樣括起來,因為 () 的優先權高於 *,少了括號語意就完全跑掉。

指針型別與所屬類別綁死。 typedef void (Base::*fn)(); 宣告的是「Base 的、無參數、回傳 void 的成員函式」。即使 Derived 繼承自 Base,也不能反過來用 void (Derived::*p)() 去接 &Base::print1。

虛函式會走動態派發。 範例刻意把 print1/print2 宣告為 virtual,因此 test1(&d, &Base::print1) 實際呼叫到的是 Derived::print1()。成員函式指標指向的是「Base 的哪個成員」,而實際執行哪一份實作,仍由物件的動態型別決定。這一點和一般函式指標很不同,也是最容易寫出錯結果的地方。

若專案使用 C++11 以上,也可以改用 std::bind 或 lambda 把成員函式指標包成一般可呼叫物件,能少掉不少 ->* 的視覺負擔:

auto f = std::bind(&Base::print1, &d);
f();
Copyright © Linux教程網 All Rights Reserved