Created
March 24, 2012 18:46
-
-
Save neocoin/2186548 to your computer and use it in GitHub Desktop.
C++ function pointer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
#include <string> | |
using namespace std; | |
class Person | |
{ | |
string name; | |
public: | |
Person(string name) | |
{ | |
this->name = name; | |
printf("%s\n", name.c_str()); | |
}; | |
const char* getName() | |
{ | |
return name.c_str(); | |
} | |
const char* getName2() | |
{ | |
return name.c_str(); | |
} | |
}; | |
typedef const char* (Person::*NamePointer)(); | |
typedef const char* (Person::*NamePointer2)(); | |
int main() | |
{ | |
Person p = Person("John"); | |
NamePointer methodPtr = &Person::getName; | |
printf("name is %s\n", (p.*methodPtr)()); | |
Person *ptr = new Person("Alice"); | |
printf("name is %s\n", (ptr->*methodPtr)()); | |
NamePointer2 not_a_class_ptr = reinterpret_cast<NamePointer2>(&Person::getName); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment