not so obvious pointers
I have a class :
class X{
public :
void f ( int ) ;
int a ;
} ;
And the task is "Inside the code provide declarations for :
- pointer to int variable of class X
- pointer to function void(int) defined inside class X
- pointer to double variable of class X"
Ok so pointer to int a will be just int *x = &a, right ? If there is no double in X can I already create pointer to double inside this class ? And the biggest pro开发者_如何转开发blem is the second task. How one declares pointer to function ?
These are called pointers to members. They are not regular pointers, i.e. not addresses, but "sort-of" offsets into an instance of the class (it gets a bit tricky with virtual functions.) So:
int X::*ptr_to_int_member;
void (X::*ptr_to_member_func)( int );
double X::*ptr_to_double_member;
You need to declare them as pointer-to-members. Pointers to members are different than usual pointers in that they are the address of a member of a structure or class, not an absolute address like regular pointers.
For more information, read this.
A pointer to any type is declared with an '*' after the type name and the variable name:
Franks_Class * p_franks_class; // Declares a pointer to an instance of Franks_Class.
The more obscure declaration is for the function:
typedef void (*My_Int_Function_Ptr)(int parameter);
which declares a type (synonym), named My_Int_Function_Ptr, a pointer to a function taking an int parameter and returning void
.
From this and a good C++ book, you should be able to answer the rest of your questions.
精彩评论