Hello!
In one of the answers I saw that the class field is defined as follows:
void(My::*z)( int );
Explain, please such a record. When is it used?
Hello!
In one of the answers I saw that the class field is defined as follows:
void(My::*z)( int );
Explain, please such a record. When is it used?
When is it used?
Such a field is used in cases where there is some external dependence on the class method. In my example, this dependence on the internal state of the object. Without the "pointer to the method" would still have to enter the additional variable State
. But in that case, the logic of the method would not be so obvious.
Here is the same example without z
:
class My{ int State; public: My( void ) : State( 0 ){} void state( int x ){ switch( State ){ case 0: if( x == 1 ){ State = 1; } break; case 1: if( x == 2 ){ State = 2; }else{ State = 1; } break; case 2: if( x == 3 ){ State = 0; } break; } } }
Obviously, in this version it is much easier to get confused in the numbers of states than in the initial one. For better orientation by code, enum
is introduced in such cases:
class My{ enum{ state_1 = 0, state_2, state_3 }; int State; public: My( void ) : State( state_1 ){} void state( int x ){ switch( State ){ case state_1: if( x == 1 ){ State = state_2; } break; case state_2: if( x == 2 ){ State = state_3; }else{ State = state_1; } break; case 2: if( x == 3 ){ State = state_1; } break; } } }
But in my opinion, even in this case, the initial version is more profitable to understand.
Source: https://ru.stackoverflow.com/questions/196991/
All Articles
state_2
, but called the one pointed to byz
at the moment. This can bestate_1
,state_2
orstate_3
. - mega