疫情期间手机直线:18622734798
当前位置:首页网站设计:基础篇 → 全部信息
应用C++成员指针注意的两个方面
更新时间:2012/11/6 点击:1429次

规则1:*需要与间接引用的对象结合,因为类内部是没有地址的,所以成员指针只是代表对象内一定的偏移
规则2: 当获取成员函数的地址(偏移地址)时,符号&是必要的,这与非成员函数指针的用法不同
用例1:
//: PointerToMemberData.cpp
#include <iostream>
using namespace std;
class Data
{
public:
int a, b, c;
void print() const
{
cout << "a = " << a << ", b = " << b
<< ", c = " << c << endl;
}
};
int main()
{
Data d, *dp = &d;
int Data::*pmInt = &Data::a;
dp->*pmInt = 47; //规则1
pmInt = &Data::b;
d.*pmInt = 48;
pmInt = &Data::c;
dp->*pmInt = 49; //规则1
dp->print();
}
用例2:
//: PointerToMemberFunction.cpp
#include <iostream>
using namespace std;
class Widget
{
public:
void f(int) const { cout << "Widget::f()\n"; }
void g(int) const { cout << "Widget::g()\n"; }
void h(int) const { cout << "Widget::h()\n"; }
void i(int) const { cout << "Widget::i()\n"; }
};
int main()
{
Widget w;
Widget* wp = &w;
void (Widget::*pmem)(int) const = &Widget::h; //规则2
(w.*pmem)(1); //规则1
(wp->*pmem)(2); //规则1
}用例3:
//: PointerToMemberFunction2.cpp
#include <iostream>
using namespace std;
class Widget
{
void f(int) const { cout << "Widget::f()\n"; }
void g(int) const { cout << "Widget::g()\n"; }
void h(int) const { cout << "Widget::h()\n"; }
void i(int) const { cout << "Widget::i()\n"; }
enum { cnt = 4 };
void (Widget::*fptr[cnt])(int) const;
public:
Widget()
{
fptr[0] = &Widget::f; //规则2
fptr[1] = &Widget::g;
fptr[2] = &Widget::h;
fptr[3] = &Widget::i;

}
void select(int i, int j)
{
if(i < 0 || i >= cnt)
return;
(this->*fptr[i])(j); //规则1,this必不可少
}
int count() { return cnt; }
};
int main()
{
Widget w;
for(int i = 0; i < w.count(); i++)
w.select(i, 47);

  • 疫情期间手机直线:18622734798    服务邮箱:service@nfree.cn     QQ:1448132697
  • 地址:天津市河西区围堤道146号华盛广场B座22楼    

    津公网安备 12010302001042号

  • CopyRight 2006~2024 All Rights Reserved 天津市华易动力信息科技有限公司