c ++:无法理解消息处理程序
c++: Not able to understand Message Handlers
实际上我是编写处理程序的新手,但不知何故我设法编写了这段代码:
#include<iostream>
using namespace std;
class test
{
public:
typedef void (test::*MsgHandler)(int handle);
test()
{
cout<<"costructor called"<<endl;
}
void Initialize()
{
add_msg_Handler(4,&test::System);
}
void System(int handle)
{
cout<<endl<<"Inside System()"<<endl;
cout<<"handle:"<<handle<<endl;
}
protected:
MsgHandler message[20];
void add_msg_Handler(int idx,MsgHandler handler)
{
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
}
};
int main()
{
test obj;
obj.Initialize();
return 0;
}
此代码运行良好,我得到的输出为:
costructor called
Inside add_msg_Handler()
handler:1
message:1
但是有几件事超出了我的范围。如果我是对的,System() 应该在这一行被调用:
add_msg_Handler(4,&test::System);
但这并没有发生。我需要帮助来纠正这个问题。
其次,我无法理解为什么会得到这样的输出:
handler:1
我的意思是处理程序如何初始化为 1.Can 有人帮我解决这个问题吗??
&test::System
不是函数调用,它是指向成员函数 test::System
.
的指针
(调用看起来像 System(0)
,如果您将它用作相关参数,则不会编译。)
如果你看一下add_msg_handler
的定义:
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
没有一个地方调用函数 handler
。
(调用看起来像 (this->*handler)(0)
或 (this->*message[idx])(0)
。)
所以该函数未被调用,因为您的代码中没有任何内容调用它。
输出是 1
因为
handler
是指向成员函数的指针
- 没有
<<
指向成员函数的指针的重载
- 是从指向成员函数的指针到
bool
的隐式转换
<<
bool
过载
- 一个非空指针被隐式转换为
true
true
默认输出为 1
。
实际上我是编写处理程序的新手,但不知何故我设法编写了这段代码:
#include<iostream>
using namespace std;
class test
{
public:
typedef void (test::*MsgHandler)(int handle);
test()
{
cout<<"costructor called"<<endl;
}
void Initialize()
{
add_msg_Handler(4,&test::System);
}
void System(int handle)
{
cout<<endl<<"Inside System()"<<endl;
cout<<"handle:"<<handle<<endl;
}
protected:
MsgHandler message[20];
void add_msg_Handler(int idx,MsgHandler handler)
{
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
}
};
int main()
{
test obj;
obj.Initialize();
return 0;
}
此代码运行良好,我得到的输出为:
costructor called
Inside add_msg_Handler()
handler:1
message:1
但是有几件事超出了我的范围。如果我是对的,System() 应该在这一行被调用:
add_msg_Handler(4,&test::System);
但这并没有发生。我需要帮助来纠正这个问题。
其次,我无法理解为什么会得到这样的输出:
handler:1
我的意思是处理程序如何初始化为 1.Can 有人帮我解决这个问题吗??
&test::System
不是函数调用,它是指向成员函数 test::System
.
的指针
(调用看起来像 System(0)
,如果您将它用作相关参数,则不会编译。)
如果你看一下add_msg_handler
的定义:
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
没有一个地方调用函数 handler
。
(调用看起来像 (this->*handler)(0)
或 (this->*message[idx])(0)
。)
所以该函数未被调用,因为您的代码中没有任何内容调用它。
输出是 1
因为
handler
是指向成员函数的指针- 没有
<<
指向成员函数的指针的重载 - 是从指向成员函数的指针到
bool
的隐式转换
<<
bool
过载
- 一个非空指针被隐式转换为
true
true
默认输出为1
。