Programing/C/C++
C++에서는 되는 캐스팅(형변환) 기법
ned3y2k
2012. 7. 12. 15:20
#include <stdio.h>
class Human {
public:
int age;
virtual void printme() {
printf("age human: %d\n", age);
}
};
class Person : public Human {
virtual void printme() {
printf("age Person: %d\n", age);
}
};
class Monkey {
public:
int age;
int position;
virtual void printme() {
printf("age monkey: %d\n", age);
}
};
int main() {
// unpredictable
Human* human = new Human();
Monkey* monkey = (Monkey*) human;
human->age=100;
printf("monkey?? age??: %d\n",monkey->age);
monkey->printme();
// predictable
human = new Person();
human->printme();
return 0;
}
결과
monkey?? age??: 100
age human: 100
age Person: 0