Point to class member

#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", 100);
   Student *ps = &s;

   Student ss("zhaoqi", 100);
   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 0;
}

在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", 100);
    Student *ps = &s;
    Student ss("zhangsan", 100);
    Student *pss = &ss;
    (s.*pdis)(1);
    (ss.*pdis)(2);
    (ps->*pdis)(1);
    (ps->*pdis)(2);

    return 0;
}

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;
}

猜你喜欢

转载自www.cnblogs.com/aelite/p/10810371.html