bind问题,求解

LaoJiu_ 2016-01-10 08:07:08

class CStudent
{
public:
void operator() (string strName, int nAge)
{
cout << strName << " : " << nAge << endl;
}
};

int main()
{

using namespace std::placeholders;

//----------#1
auto one = bind(CStudent(), "mi", _1);
one(12);

//--------#2
CStudent student;
auto two = bind(&CStudent::operator(), student, "mi", _1);
two(12);

return 0;
}


#1与#2,前者没有申明类变量,直接CStudent()这样就用了;后者需要申请类的一个变量,并且在bind使用中,娅需要把这个变量加进去,这两者区别是什么,前者为什么可以那样用?

还有一个疑问,就是bind的第一个参数不是要绑定一个地址么(我是这么理解的,错了请指正),为什么在绑定一个普通函数时只需要把函数名写进去就行了,但是在绑定类/结构体内函数时就要加一个&?
...全文
191 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
paschen 版主 2016-01-12
  • 打赏
  • 举报
回复
数组名、函数名都不是指针,普通的函数名可以转化为函数指针,但成员函数不行,需要加&
zhouxiaofeng1021 2016-01-12
  • 打赏
  • 举报
回复
http://www.cnblogs.com/sld666666/archive/2010/12/14/1905980.html
ngo tong 2016-01-11
  • 打赏
  • 举报
回复
Defined in header <functional> template< class F, class... Args > /*unspecified*/ bind( F&& f, Args&&... args ); (1) (since C++11) template< class R, class F, class... Args > /*unspecified*/ bind( F&& f, Args&&... args ); (2) (since C++11) The function template bind generates a forwarding call wrapper for f. Calling this wrapper is equivalent to invoking f with some of its arguments bound to args. Parameters f - Callable object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments args - list of arguments to bind, with the unbound arguments replaced by the placeholders _1, _2, _3... of namespace std::placeholders from: http://en.cppreference.com/w/cpp/utility/functional/bind
yshuise 2016-01-10
  • 打赏
  • 举报
回复
CStudent()这个便是临时对象,bind函数再加个括号(看源代码),就成了调用operator()
十万个纳尼 2016-01-10
  • 打赏
  • 举报
回复
这是硬性规定,也就是通常说的语法,普通函数函数名就是函数地址,而成员函数必须加上&,没有为什么可言,就好比1+1=2.

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧