函数作为参数的传递
2009-06-08 15:27
148 查看
函数作为参数的传递
要把函数作为参数传递时,有两种方法:1.函数指针;2.仿函数.
函数指针的方法比较常用:
typedef
int
(
*
pf)(
int
,
int
);
int
f(pf p,
int
a,
int
b){
return
p(a,b);
}
int
add(
int
a,
int
b){
return
a
+
b;
}
int
main(){
cout
<<
f(add,
1
,
2
)
<<
endl;
}
但用函数指针时,它无法持有自己的状(局部状态,local states),仿函数就克服了这个缺点.
仿函数:
template
<
class
T
>
class
Sum{
T res;
public
:
Sum(T i
=
0
):res(i){}
void
operator
()(T x){
res
+=
x;
}
T result()
const
{
return
res;
}
};
template
<
class
T
>
struct
testplus{
T
operator
()(
const
T
&
x,
const
T
&
y)
const
{
return
x
+
y;
}
};
int
main(){
list
<
double
>
l;
l.push_back(
1.0
);
l.push_back(
2.0
);
Sum
<
double
>
s;
s
=
for_each(l.begin(),l.end(),s);
cout
<<
"
the sum is
"
<<
s.result()
<<
endl;
//
cout<<plus<int>(1,2)<<endl;//error for lost ()
testplus
<
int
>
plusobj;
cout
<<
plusobj(
1
,
2
)
<<
endl
<<
testplus
<
int
>
()(
2
,
2
);
}
要把函数作为参数传递时,有两种方法:1.函数指针;2.仿函数.
函数指针的方法比较常用:
typedef
int
(
*
pf)(
int
,
int
);
int
f(pf p,
int
a,
int
b){
return
p(a,b);
}
int
add(
int
a,
int
b){
return
a
+
b;
}
int
main(){
cout
<<
f(add,
1
,
2
)
<<
endl;
}
但用函数指针时,它无法持有自己的状(局部状态,local states),仿函数就克服了这个缺点.
仿函数:
template
<
class
T
>
class
Sum{
T res;
public
:
Sum(T i
=
0
):res(i){}
void
operator
()(T x){
res
+=
x;
}
T result()
const
{
return
res;
}
};
template
<
class
T
>
struct
testplus{
T
operator
()(
const
T
&
x,
const
T
&
y)
const
{
return
x
+
y;
}
};
int
main(){
list
<
double
>
l;
l.push_back(
1.0
);
l.push_back(
2.0
);
Sum
<
double
>
s;
s
=
for_each(l.begin(),l.end(),s);
cout
<<
"
the sum is
"
<<
s.result()
<<
endl;
//
cout<<plus<int>(1,2)<<endl;//error for lost ()
testplus
<
int
>
plusobj;
cout
<<
plusobj(
1
,
2
)
<<
endl
<<
testplus
<
int
>
()(
2
,
2
);
}
相关文章推荐
- C语言中将二维数组作为参数传递给函数的方法
- C语言中数组名作为参数进行函数传递
- 关于将函数的地址作为参数传递给另一个函数调用
- 数组作为函数参数传递
- 指针作为函数参数传递
- 多维动态数组作为函数传递参数
- 数组作为函数参数传递
- 怎样把数组作为参数传递给函数
- 函数指针作为参数传递给函数
- 如何将二维数组作为函数的参数传递
- C++指针作为函数的参数进行传递时注意的问题
- C语言二维数组作为函数参数传递剖析
- 如何将二维数组作为函数的参数传递
- 数组作为函数参数传递时
- python的raw_input()函数。 函数的可变对象和不可变对象作为参数传递。
- 指针作为函数的参数传递的问题
- 对象作为函数参数时调用拷贝构造函数、引用做函数参数时只是传递地址
- C语言二维数组作为函数参数传递
- C语言中将二维数组作为参数传递给函数的方法
- 关于二维数组作为参数传递给函数的问题