#include <iostream.h>
class Student
{
friend ostream & operator<<(ostream &
out, const Student & s);
public:
int age;
int studentNumber;
char * name;
char * address;
Student(char * theirName, char * theirAddress, int
theirAge, int theirStNum) :
name(theirName), address(theirAddress),
age(theirAge), studentNumber(theirStNum) {}
};
ostream & operator<<(ostream & out, const Student &
s) {
out << s.name;
return out;
}
//function that accesses member data of object through a member pointer
void displayIntField(const Student & s, int Student::* mp) {
cout << "IntValue = " << s.*mp <<
"\n";
}
void main( )
{
Student lou("Lou", "45 Elgin St.", 25, 12345);
Student sue("Sue", "145 Sussex Drive.", 23, 22222);
int x = 5;
int * ip = &x;
cout << "the int: " << *ip << " The student:
" << lou << "\n";
int Student::* stdNumPtr = &Student::studentNumber;
displayIntField(lou, &Student::age);
displayIntField(lou, stdNumPtr);
displayIntField(sue, &Student::age);
displayIntField(sue, stdNumPtr);
//You cannot mix the pointer types
//int * p = &Student::age; ERROR
//int Student::* stdp2 = &x; ERROR
}
/*
the int: 5 The student: Lou
IntValue = 25
IntValue = 12345
IntValue = 23
IntValue = 22222
*/
#include <iostream.h>
#include <string.h>
void sayAgain(const char * str, int n){
for(int i=0; i<n; i++) cout <<
str << "\n"; }
void sayTimes(const char * str, int n){
cout << str << " times "
<<
n << "\n"; }
void saySpace(const char * str, int n){
for(unsigned i=0; i <
strlen(str);
i++) {
cout << str[i];
for(int j=0; j<n; j++) cout <<
" ";
}
cout << "\n";
}
void doit(const char * string, int times,
void
(*f) (const char *, int)) {
f(string, times);
}
void main(){
doit("Hey", 3, &sayAgain);
doit("Hello", 5, &sayTimes);
doit("Bye", 5, &saySpace);
}
Output:
Hey
Hey
Hey
Hello times 5
B
y e
One can take the address of a method and then apply that method to an object.
#include <iostream.h>Method Pointers and Function Pointers cannot be mixed.
char * (fp)(void);
char * (Person:: mp)(void);
char * foo() {return "George";}
fp = &foo;
//OK
fp = foo; //OK
fp = &Person::getName;
//ERROR