class test{
public:
string str;
// other data members
test(const string &s) : str(s) {}
const string & get() {/*....*/}
// other member functions
};
int main() {
test Test("pointer to class member");
string test::* string_p = &test::str;
const string & (test::* pmf)() = &test::get;
Test.str = "pointer_to_class_member";
cout << Test.get() << endl;
Test.*string_p = "pointer to class member";
cout << (Test.*pmf)() << endl;
//...
}
pointer to class member ,不是指向具體物件的 pointer
而是一種特殊的 pointor 可以藉由任一 class 物件喚起~
但實用價值尚待研究!
在上述 source 中,
test::*
,代表屬於 class test 的 pointer
因此,
string_p
及
pmf
都是屬於 class test 的 pointer to class member
cout << Test.get() << endl;
cout << (Test.*pmf)() << endl;
這兩個敘述可以畫上等號,一者是直接喚起 get()
而另一者是藉由 pointer to class member 喚起。
此處,(Test.*pmf)()若少了小括號
則會變成:
Test.*pmf()
會被解讀成:
Test.*(pmf())
將引發 complie-time error