Pointer to Member Operators
Educate yourself about accessing the structure members using pointer to member operators.
We'll cover the following...
Problem
Write a program to access the struct
members using the pointer to member operators .*
and ->*
.
Sample run
Here’s what you should see when you run the program.
10 3.14
10 3.14
20 6.28
20 6.28
30 9.22
40 7.33
60 8.88
Coding solution
Here is a solution to the problem above.
Press + to interact
// Pointer to member operators#include <iostream>struct sample{int a ;float b ;} ;int main( ){sample so = { 10, 3.14f } ;int sample::*p1 = &sample::a ;float sample::*p2 = &sample::b ;std :: cout << so.*p1 << "\t" << so.*p2 << std :: endl ;sample *sp ;sp = &so ;std :: cout << sp->*p1 << "\t" << sp->*p2 << std :: endl ;// we can even assign new valuesso.*p1 = 20 ;sp->*p2 = 6.28f ;std :: cout << so.*p1 << "\t" << so.*p2 << std :: endl ;std :: cout << sp->*p1 << "\t" << sp->*p2 << std :: endl ;sample soarr[ ] = {{ 30, 9.22f },{ 40, 7.33f },{ 60, 8.88f }} ;for ( int i =0 ; i <= 2 ; i++ )std :: cout << soarr[ i ].*p1 << "\t" << soarr[ i ].*p2 << std :: endl ;return 0 ;}
Explanation
To carry out the access and the ...