您的位置:首页 > 其它

函数指针,成员函数指针,重载函数指针

2014-05-30 16:04 302 查看
指向函数的指针

函数的类型由它的返回值和参数列表决定, 但函数不能返回一个函数类型。

01
int
fce(
const
char
*,
 ... );
02
int
fc(
const
char
*
 );
03
04
//
 point to fce
05
typedef
int
(*PFCE)(
const
char
*,
 ... );
06
//
 point to fc
07
typedef
int
(*PFC)(
const
char
*
 );
08
09
//
 Initialization
10
PFCE
 pfce = fce;
11
PFC
 pfc = fc;
12
13
//
 Invoke the functions
14
pfce();
15
pfc();
指向重载函数的指针

在两个函数指针类型之间不能进行类型转换, 必须严格匹配才能找到相应的函数。

1
void
ff(
const
char
*
 );
2
void
ff(
 unsigned
int
);
3
4
//
 Error: No Match,not available parameter list
5
void
(*pf)(
int
)
 = ff;
6
//
 Error: No Match,not available return type
7
double
(*pf2)(
const
char
*
 )) = ff;
指向类实例成员函数的指针

指向类实例成员函数的指针必须匹配三个方面:参数类型和个数,返回类型,所属类类型。

01
class
Screen
02
{
03
public
:
04
int
Add(
int
lhs,
int
rhs);
05
int
Del(
int
lhs,
int
rhs
 );
06
void
ShowNumber(
int
value);
07
};
08
09
typedef
int
(Screen::*OPE)(
int
,
int
);
10
typedef
void
(Screen::*SHOW)(
int
);
11
12
OPE
 ope = &Screen::Add;
13
SHOW
 show = &Screen::ShowNumber;
14
15
Screen
 scr;
16
 
17
//
 Invoke its own member
18
int
value
= scr.Add(10,20);
19
scr.ShowNumber(value);
20
21
//
 Invoke the function point
22
value
= (scr.*ope)(10,20);
23
(scr.*show)(value);
指向类静态成员函数的指针

指向类静态成员函数的指针属于普通指针。

view
source

print?

01
class
Screen
02
{
03
public
:
04
static
int
Add(
int
lhs,
int
rhs);
05
};
06
07
typedef
int
(*OPE)(
int
,
int
);
08
09
OPE
 ope = &Screen::Add;
10
11
int
value
= ope(10,20);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: