Point to class member

时间:2021-12-12 08:06:29
#include <iostream>
using namespace std; class Student
{
public:
Student(string n, int nu):name(n),num(nu){}
string name;
int num;
}; int main()
{
Student s("zhangsi", );
Student *ps = &s; Student ss("zhaoqi", );
Student *pss = &ss;
//string *ps = &s.name;//the action destroy the encapsulation
//下面讲的指针,是指向类层面的指针,而不是对象层面
//要想使用,还要跟具体的对象产生关系
string Student:: *psn = &Student::name;
cout << s.*psn << endl;
cout << ps->*psn << endl; cout << ss.*psn << endl;
cout << pss->*psn << endl; return ;
}

在c++中

.*:Pointer to member

->*:Pointer to member

Point to class function

#include <iostream>
using namespace std; class Student
{
public:
Student(string n, int nu):name(n),num(nu){}
void dis(int idx)
{
cout << "idx:" << idx << "name:" << name << "number:" << num << endl;
}
string name;
int num;
}; int main()
{
void (Student::*pdis)(int idx) = &Student::dis;
Student s("zhangsan", );
Student *ps = &s;
Student ss("zhangsan", );
Student *pss = &ss;
(s.*pdis)();
(ss.*pdis)();
(ps->*pdis)();
(ps->*pdis)(); return ;
} test1:
#include <iostream>
using namespace std; struct Point
{
    int add(int x, int y)
    {
        return x + y;
    }
    int minus(int x, int y)
    {
        return x - y;
    }
    int multi(int x, int y)
    {
        return x * y;
    }
    int div(int x, int y)
    {
        return x / y;
    }
}; int oper(Point &p, int (Point::*pf)(int x, int y), int x, int y)
{
    return (p.*pf)(x,y);
}
typedef int (Point::*PF)(int x, int y);
int main()
{
    Point p;
    PF pf = &Point::add;
    cout << oper(p, pf, 1, 2);
    return 0;
}

更加隐蔽的接口

#include <iostream>
using namespace std;
class Game
{
public:
Game()
{
pf[] = &Game::f;
pf[] = &Game::g;
pf[] = &Game::h;
pf[] = &Game::l;
}
void select(int i)
{
if (i >= && i <= )
{
(this->*pf[i])(i);
}
}
private:
void f(int idx) { cout << "void f(int idx)" << "idx:" << idx << endl; }
void g(int idx) { cout << "void g(int idx)" << endl; }
void h(int idx) { cout << "void h(int idx)" << endl; }
void l(int idx) { cout << "void l(int idx)" << endl; }
enum{
nc =
}; void (Game::*pf[nc])(int idx);
}; int main()
{
Game g;
g.select();
g.select();
g.select();
return ;
}