成员变量指针和成员函数指针

#include <iostream>

using namespace std;
class  A
{
public:
    int m_i;
    string m_str;
    void ptf()
    {
        printf("%d, %s\n",m_i,m_str.c_str());
    }
};

int main(void)
{
    A a,*pa = &a;

    int A::*pi = &A::m_i;
    string A::*pStr = &A::m_str;
    //成员变量指针
    a.*pi = 10;
    pa->*pi = 20;
    a.*pStr = "1231";
    pa->*pStr = "2345";
    //成员函数指针
    void (A::*pPtf)() = &A::ptf;
    (a.*pPtf)();    //必须(a.*pPtf)加括号
    (pa->*pPtf)();
    return 0;
}

静态成员函数指针和普通函数指针一样

另外使用成员指针需要使用

#include <iostream>

猜你喜欢

转载自blog.csdn.net/u013566722/article/details/79726901