C++中指向类成员指针的用法
C++中,指向類的成員指針包含兩種:
(1).指向類的成員函數(shù)的指針:
? ? 類型 (類名::* 函數(shù)成員指針名)(參數(shù)表);
? ? 函數(shù)成員指針名 = &類名::函數(shù)成員名;
也可將以上兩條語句調(diào)整為一條語句:
? ? 類型 (類名::* 函數(shù)成員指針名)(參數(shù)表) = &類名::函數(shù)成員名;
類成員函數(shù)指針,是C++語言的一類指針數(shù)據(jù)類型,用于存儲一個指定類具有給定的形參列表與返回值類型的成員函數(shù)的訪問信息。
使用::*聲明一個成員指針類型,或者定義一個成員指針變量。使用.*或者->*調(diào)用類成員函數(shù)指針?biāo)赶虻暮瘮?shù),這時必須綁定于成員指針?biāo)鶎兕惖囊粋€實例的地址。
(2).指向類的數(shù)據(jù)成員的指針:
? ? 類型 類名::* 數(shù)據(jù)成員指針名;
? ? 數(shù)據(jù)成員指針名 = &類名::數(shù)據(jù)成員名;
也可將以上兩條語句調(diào)整為一條語句:
? ? 類型 類名::* 數(shù)據(jù)成員指針名 = &類名::數(shù)據(jù)成員名;
以下是測試代碼:
class Ops {
public:Ops() = default;Ops(const int* p1, const int* p2) : value1_(p1), value2_(p2) {}Ops(const std::string& str) : addr_(str) {}int add(int a, int b) { return (a + b); }void sub(int a, int b) { fprintf(stdout, "sub: %d\n", (a - b)); }int (Ops::* op)(int, int);const int *value1_ = nullptr, *value2_ = nullptr;std::string addr_ = "";
};const int* Ops::* select()
{std::random_device rd; std::mt19937 generator(rd()); // 每次產(chǎn)生不固定的不同的值std::uniform_int_distribution<int> distribution(0, 2);if (distribution(generator)) return &Ops::value1_;else return &Ops::value2_;
}void print(int a, int b, Ops& ops, int (Ops::* fp)(int, int))
{int value = (ops.*fp)(a, b);fprintf(stdout, "value: %d\n", value);
}int test_class3()
{// 類的成員函數(shù)int (Ops::* func1)(int, int); // 一個類成員函數(shù)指針變量func1的定義func1 = &Ops::add; // 類成員函數(shù)指針變量func1被賦值Ops ops, *p;p = &ops;int ret = (ops.*func1)(2, 3); // 對實例ops,調(diào)用成員函數(shù)指針變量func1所指的函數(shù)fprintf(stdout, "add: %d\n", ret);ret = (p->*func1)(-2, -3); // 對p所指的實例,調(diào)用成員函數(shù)指針變量func1所指的函數(shù)fprintf(stdout, "add2: %d\n", ret);void (Ops::* func2)(int, int);func2 = &Ops::sub; // 函數(shù)指針賦值要使用&(ops.*func2)(9, 3); (ops.*func2)(3, 9);Ops ops2;int (Ops::* func3)(int, int) = &Ops::add; // 定義類成員函數(shù)指針并賦值ret = (ops2.*func3)(7, 4);fprintf(stdout, "add3: %d\n", ret);Ops ops5;print(1, 6, ops5, &Ops::add);Ops ops6;ops6.op = &Ops::add;fprintf(stdout, "value2: %d\n", (ops6.*(ops6.op))(-2, -6));// 類的數(shù)據(jù)成員const int a = 13, b = 15;Ops ops3(&a, &b);const int* Ops::* value = select();fprintf(stdout, "value1: %d\n", *(ops3.*value));std::string Ops::* str = &Ops::addr_; // 定義時和類關(guān)聯(lián)Ops ops4("https://blog.csdn.net/fengbingchun");fprintf(stdout, "addr: %s\n", (ops4.*str).c_str()); // 使用時和對象關(guān)聯(lián)Ops ops7;ops7.addr_ = "https://github.com/fengbingchun"; // 直接訪問fprintf(stdout, "addr is: %s\n", ops7.addr_.c_str());std::string Ops::* addr2 = &Ops::addr_;ops7.*addr2 = "https://blog.csdn.net/fengbingchun"; // 通過指向成員的指針進行訪問fprintf(stdout, "addr is: %s\n", ops7.addr_.c_str());return 0;
}
執(zhí)行結(jié)果如下圖所示:
GitHub:https://github.com/fengbingchun/Messy_Test
總結(jié)
以上是生活随笔為你收集整理的C++中指向类成员指针的用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++11中头文件type_traits
- 下一篇: 在Ubuntu上编译opencv 2.4