We know that to access a structure member we use a '.' or '->' operator. Also, to dereference a pointer we use the '*' operator. To access the structure element through this pointer we need '.' or '->' to reach the element and '*' to deference the pointer. To carry out the access & deferenceing simultaneously, C++ provides two new operators: '*' and '->'. These are known as pointer to member operators.
#include<iostream.h>
struct sample
{
int a;
float b;
int *c;
float *d;
int **e;
float **f;
};
void main()
{
int sample::*p1=&sample::a;
float sample::*p2=&sample::b;
int *sample::*p3=&sample::c;
float *sample::*p4=&sample::d;
int **sample::*p5=&sample::e;
float**sample::*p6=&sample::f;
sample so={10,3.14,&so.a,&so.b,&so.c,&so.d};
sample *sp;
sp=&so;
//pointer to member operators using *
cout<<endl<<so.*p1<<endl<<so.*p2;
cout<<endl<<*(so.*p3)<<endl<<*(so.*p4);
cout<<endl<<**(so.*p5)<<endl<<**(so.*p6);
// pointer to member operators using ->
cout<<endl<<sp->*p1<<endl<<sp->*p2;
cout<<endl<<*(sp->*p3)<<endl<<*(sp->*p4);
cout<<endl<<**(sp->*p5)<<endl<<**(sp->*p6);
//store new values
*(so.*p3)=20;
**(sp->*p6)=6.28;
//output change values through p1 & p2
cout<<endl<<so.*p1<<endl<<so.*p2;
}
#include<iostream.h>
struct sample
{
int a;
float b;
int *c;
float *d;
int **e;
float **f;
};
void main()
{
int sample::*p1=&sample::a;
float sample::*p2=&sample::b;
int *sample::*p3=&sample::c;
float *sample::*p4=&sample::d;
int **sample::*p5=&sample::e;
float**sample::*p6=&sample::f;
sample so={10,3.14,&so.a,&so.b,&so.c,&so.d};
sample *sp;
sp=&so;
//pointer to member operators using *
cout<<endl<<so.*p1<<endl<<so.*p2;
cout<<endl<<*(so.*p3)<<endl<<*(so.*p4);
cout<<endl<<**(so.*p5)<<endl<<**(so.*p6);
// pointer to member operators using ->
cout<<endl<<sp->*p1<<endl<<sp->*p2;
cout<<endl<<*(sp->*p3)<<endl<<*(sp->*p4);
cout<<endl<<**(sp->*p5)<<endl<<**(sp->*p6);
//store new values
*(so.*p3)=20;
**(sp->*p6)=6.28;
//output change values through p1 & p2
cout<<endl<<so.*p1<<endl<<so.*p2;
}
No comments:
Post a Comment