admin write
blogbloglocation loglocation logtag listtag listguest bookguest book
Add to favoritesrss feed

function pointer tutorial의 첫 단락을 보고 간단한 예제를 만들어 보았습니다.

클래스 A는 fpShout라는 function pointer를 member variable로 가지고 있습니다.

class A{
private:
void (*fpShout)();
public:
A() { fpShout = NULL; };
void setShout(void (*fpFunc)()) { fpShout = fpFunc; };
void Shout()
{
if (fpShout == NULL)
cout << “fpShout is NULL” << endl;
else
fpShout();
};
};

전역으로 ShoutA()와 ShoutB()라는 함수를 선언하고 정의합니다.

void ShoutA() { cout << “A” << endl; };
void ShoutB() { cout << “B” << endl; };

클래스 B는 member variable로 클래스 A를 가지고 있으며  Shout()를 호출하면 자신의 메소드인 ShoutC()를 A에게 세팅하여 A의 Shout()를 호출합니다.

class B
{
private:
static void ShoutC() { cout << “C” << endl; };
A a;
public:
void Shout()
{
a.setShout(&ShoutC);
a.Shout();
};
};

main함수에서는 먼저 fpShout에 아무 것도 할당하지 않은 상태로 A의 인스턴스의 Shout()를 호출하고, 그 후 전역 함수인 ShoutA()와 ShoutB()를 각각 할당한 후 A의 Shout()를 호출합니다. 마지막으로 B의 인스턴스에 대해 Shout()를 호출합니다.

int main()
{
A a;
a.Shout();
a.setShout(&ShoutA);
a.Shout();
a.setShout(&ShoutB);
a.Shout();
B b;
b.Shout();
}

function pointer를 member variable로 가질 경우 먼저 NULL로 설정한 후 항상 NULL 체크를 한 후에 실행될 수 있도록 해야 합니다.

위 code를 컴파일해서 실행해 보면 아래와 같은 결과가 나옵니다.

fpShout is NULL
A
B
C

Creative Commons License

트랙백 보낼 주소 :: http://devnuri.com/trackback/2

댓글을 달아주세요:: 네티켓은 기본, 스팸은 사절

C++ Quiz

2007/12/12 14:44
간단한 퀴즈입니다.
cout << "Hello World!" << endl;

C++ 책 1장부터 우리가 사용하는 cout의 정체는 뭘까요?
1) class
2) object
3) function
4) template
5) keyword
6) none of the above
Creative Commons License
태그 C++

트랙백 보낼 주소 :: http://devnuri.com/trackback/1

댓글을 달아주세요:: 네티켓은 기본, 스팸은 사절