How to Use the C ++ signal slot
1. Why use the signal slot.
A. The event sources and subscriber can be separated.
B. Reduce coupling. The event source only needs to expose the least information to the outside world, and internal changes do not affect external behaviors.
C. Reduce Code complexity and distribute different event processing codes to subscriber.
2. How to use the information slot
A. Include the header file, # include "sigslot. H" using namespace sigslot;
B. an internal signal slot object is known in the event source class, for example, signal1 <constcstring &> sltloginfail;. The signal1 template indicates that there is only one parameter. and so on, there may be up to a dozen templates.
C. inherit the event subscriber class from has_slots <>, class clogindlg: Public cdialog, public has_slots <>.
D. Define the event processing function in the event subscriber class. Void onloginfail (const cstring & strerrormsg); the parameter must match the signal slot defined earlier.
E. Actively subscribe to the signal slot in the event subscriber initialization function. G_objhero.sltloginfail.connect (this, & clogindlg: onloginfail );
F. Trigger Signal when an event source event is generated. g_objhero.sltloginfail (szmsg );
G. process the event in the onloginfail function of the event subscriber.
H. log out of the onloginfail slot, g_objhero.sltloginfail.disconnect (this), when there is no need to worry about the event or when the subscriber exits. If it is forgotten, memory leakage will occur.
3. Sample Code
// Signtest. cpp: defines the entry point for the console application.
//
# Include "stdafx. H"
# Pragma warning (Disable: 4786)
# Include "sigslot. H"
# Include "iostream"
# Include <string>
Using namespace STD;
Using namespace sigslot;
Class chero
{
Public:
Chero: chero ()
{
}
Chero ::~ Chero ()
{
}
Signal1 <int> sltonlifechange;
Signal1 <STD: String> sltonheroname;
Signal1 <STD: String> * Get (void)
{
Return & sltonheroname;
}
Void onmouseclicked ()
{
Sltonheroname (m_heroname );
}
Void changelife (INT nlife)
{
M_nlife = nlife;
Sltonlifechange (m_nlife );
}
PRIVATE:
Int m_nlife;
STD: String m_heroname;
};
Class lifebar: Public has_slots <>
{
// Protected:
Public:
Void onlifechange (INT herolife)
{
Cout <"lifebar refresh hero life" }
Void onsetheroname (const STD: string name)
{
Cout <name <"/N ";
}
};
/// Main character panel
Class heropane: Public has_slots <>
{
Public:
Void onlifechange (INT herolife)
{
Cout <"heropane refresh hero life" }
};
Int main (INT argc, char * argv [])
{
Chero hero;
Lifebar bar;
Heropane pane;
Hero. sltonlifechange. Connect (& Bar, & lifebar: onlifechange );
Hero. sltonlifechange. Connect (& pane, & heropane: onlifechange );
Hero. Get ()-> connect (& Bar, & lifebar: onsetheroname );
/// Trigger Signal
Hero. changelife (10 );
Hero. onmouseclicked ();
Hero. sltonlifechange. Disconnect (& bar );
Hero. sltonlifechange. Disconnect (& pane );
Hero. sltonheroname. Disconnect (& bar );
Return 0;
}