您的位置:首页 > 其它

指向类数据成员、类成员函数的指针

2017-12-07 15:50 246 查看

指向类数据成员、类成员函数的指针(非静态)

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>

#if 0

----指向类 数据成员的指针 实际上是指向类的

定义
<数据类型><类名>::*<指针名>

赋值&初始化
<数据类型><类名>::*<指针名>[=&<类名>::<非静态数据成员>]

指向类成员指针小结:
与普通意义上的指针不一样。存放的是偏移量。从类的起始地址的偏移量
指向非静态成员函数时,必须用类名作限定符,使用时则必须用类的实例作限定符。
指向静态成员函数时,则不需要使用类名作限定符

----指向类 成员函数的指针 也是指向类的

定义
<数据类型>(<类名>::*<指针名>)(<参数列表>)
赋值&初始化

<函数类型>(<类名>::*<指针名>)(<参数列表>)[=&<类名>::<非静态成员函数>]

#endif

class Student
{
public:
Student(string na, int n):name(na), num(n){}

void func()
{
cout << "class Student Member function" << endl;
}

string name;
int num;
};

int _tmain(int argc, _TCHAR* argv[])
{
Student s1("zhaosi", 23); //栈上的对象
Student s2("liuneng", 23);

//定义时 不需要用到对象
string Student::* pn = &Student::name; //数据成员必须是非静态的
int Student::*pi = &Student::num;

//使用的时候 需要利用对象来调用
cout << s1.*pn << endl;
cout << s2.*pn << endl;
//此时*pn 相当于一个接口 只要是该类的对象就可以调用

cout << "======================================" << endl;

Student *ps = new Student("liming", 45); //在堆上的对象

cout << ps->*pi << endl; //利用new出的指针访问用->
cout << ps->*pn << endl;

cout << "======================================" << endl;

void(Student::*pf)() = &Student::func; //注意后面不要加()
//函数的指针,指针类型是函数,所以需要有 返回类型(void) 和参数()

(s1.*pf)(); //使用时也需要对象来调用 固定格式
(s2.*pf)(); //一定要加()
(ps->*pf)();

return 0;
}

指向静态类成员的指针

#include <iostream>
using namespace std;

#if 0

//指向静态类成员的指针

指向类静态成员函数、数据成员的指针:

和普通指针相同,在定义时无须和类相关联,
在使用时也无须和具体的对象相关联

#endif

class A
{
public:
static void dis();
static int data;
};

void A::dis()
{
cout<<data<<endl;
}

int A::data = 100;

int main()
{
int *p = &A::data;
cout << *p << endl;
void(*pfunc)() = &A::dis;
pfunc();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: