C++ 함수 객체 – Function Object
- 함수 객체 (Function Object)
– 함수처럼 동작하는 객체 – operator( )
– ( ) 연산자를 오버로딩 하여 객체를 함수처럼 사용
– ( ) 연산자 = 함수 호출 연산자
#include <iostream>
using namespace std;
class Sum
{
public:
int operator()(int n1, int n2) {
return n1 + n2;
}
};
void main()
{
Sum s;
cout << "Sum(5, 10) : " << s(5, 10) << endl;
}
<출력 결과>
Sum(5, 10) : 15
Sum 클래스에서 함수 호출 연산자 오버로딩하여 5, 10을 받고
두 데이터를 서로 더하여 반환하는 연산자 정의
정확히 말해 cout<< 부분의 s(5,10) 은 .operator( )가 생략된 형태
원형 : s.operator( )(5, 10)
- 함수 객체 사용 이유
– 사용시 속성을 지닐 수 있는 것이 가능
– 일반적인 함수보다 처리 속도가 빠름
– 각각의 함수 객체는 서로 다른 타입을 지님
#include <iostream>
using namespace std;
class Count
{
private:
int total;
public:
Count(int tt) : total(tt) {}
int operator()(int value) {
return total += value;
}
};
void main()
{
Count c(0);
cout << "c(100): " << c(100) << endl;
cout << "c.operator(100): " << c.operator()(100) << endl;
cout << "c(200): " << c(200) << endl;
cout << "c.operator(200): " << c.operator()(200) << endl;
cout << "c(1000): " << c(1000) << endl;
}
<출력 결과>
c(100): 100
c.operator(100): 200
c(200): 400
c.operator(200): 600
c(1000): 1600