멤버함수 포인터 사용예시

조한별·2022년 4월 5일
0
#include <iostream>

using namespace std;

class Person
{
public:
	void print(int i)
	{
		cout << i << endl;
	}
};

int main()
{
	using FuncType = void (Person::*)(int);
	FuncType fn = &Person::print;
	//위의 코드는 아래의 두 형태와 같다.
	//
	//1.
	//typedef void (Person::* FuncType)(int);
	//FuncType fn = &Person::print;
	//
	//2.
	//void (Person:: * fn)(int) = &Person::print;

	Person person;
	(person.*fn)(1);
}

결과

1

funtional을 인클루드하여 하는 방법. 결과는 동일하다.

#include <iostream>
#include <functional>

using namespace std;

class Person
{
public:
	void print(int i)
	{
		cout << i << endl;
	}
};

int main()
{
	function<void(Person*, int)> func = &Person::print;

	Person person;
	func(&person, 1);
}

print() 멤버함수가 static일 때. 결과는 동일하다.

#include <iostream>

using namespace std;

class Person
{
public:
	static void print(int i)
	{
		cout << i << endl;
	}
};

int main()
{
	void (*fn)(int) = &Person::print;
	fn(1);
}
profile
게임프로그래머 지망생

0개의 댓글