//Listing 15.10 Pointers to member functions using virtual methods
#include <iostream>
using namespace std;
class Mammal
{
public:
Mammal():itsAge(1) { }
virtual ~Mammal() { }
virtual void Speak() const = 0;
virtual void Move() const = 0;
protected:
int itsAge;
};
class Dog : public Mammal
{
public:
void Speak()const { cout << "Woof!\n"; }
void Move() const { cout << "Walking to heel...\n"; }
};
class Cat : public Mammal
{
public:
void Speak()const { cout << "Meow!\n"; }
void Move() const { cout << "slinking...\n"; }
};
class Horse : public Mammal
{
public:
void Speak()const { cout << "Winnie!\n"; }
void Move() const { cout << "Galloping...\n"; }
};
int main()
{
void (Mammal::*pFunc)() const =0;
Mammal* ptr =0;
int Animal;
int Method;
bool fQuit = false;
while (fQuit == false)
{
cout << "(0)Quit (1)dog (2)cat (3)horse: ";
cin >> Animal;
switch (Animal)
{
case 1: ptr = new Dog; break;
case 2: ptr = new Cat; break;
case 3: ptr = new Horse; break;
default: fQuit = true; break;
}
if (fQuit)
break;
cout << "(1)Speak (2)Move: ";
cin >> Method;
switch (Method)
{
case 1: pFunc = Mammal::Speak; break;
default: pFunc = Mammal::Move; break;
}
(ptr->*pFunc)();
delete ptr;
}
return 0;
}
'Language > C & C Plus' 카테고리의 다른 글
[TIP] 특정한 메모리를 읽으려면?? (0) | 2012.07.13 |
---|---|
[C] 홀수의 합 빼기 짝수의 합 2가지 버전 (0) | 2012.07.13 |
[C++] 멤버함수에 대한 포인터 (0) | 2012.07.13 |
[C++] typedef를 사용한 함수 포인터 (0) | 2012.07.13 |
[C++] 함수포인터(다른 함수에 전달하기) (0) | 2012.07.13 |