#include <iostream>

#include <algorithm>

using namespace std;


/**********************/

/*

class Equal {

int x, y;

public :

Equal() {}

Equal(int x, int y) { x = this->x; y = this->y; }

~Equal() {}

bool cmp_func()

{

return x == y  ? true : false;

}

};


int main()

{

Equal cmp(2, 2);

cout << cmp.cmp_func() << endl;

return 0;

}

*/ 

/******* 함수 객체 사용 ***************/ 

class Equal {

int x, y;

public:

Equal() {}

~Equal() {}

bool operator() (int x, int y)

{

return x == y ? true : false;

}

};


int main()

{

Equal cmp;

if (cmp(2, 2))

{

cout << "같다" << endl;

}

else

{

cout << "다르다" << endl;

}


return 0;

}

'Programing > C++' 카테고리의 다른 글

ReverseString  (0) 2015.12.02
클래스 템플릿 비교  (0) 2015.09.04
함수 객체  (0) 2015.09.04
멤버 함수 포인터 선언  (0) 2015.09.04
형변환 연산자 오버로딩  (0) 2015.09.04
Posted by kimmayer

2015. 9. 4. 11:23 Programing/C++

함수 객체

함수 객체는 함수처럼 동작하는 객체, 함수처럼 동작하려면 객체가 '()' 연산자를 정의해야 한다.

즉 () 연산자를 오버로딩한 객체가 함수 객체


#include <iostream>

#include <algorithm>

using namespace std;


struct Functor1 {

void operator() (int n)

{

cout << n << " ";

}

};

struct Functor2 {

void operator() (int n)

{

cout << n*n << " ";

}

};

struct Functor3 {

void operator() (int n)

{

cout << "정수 : " << n << endl;

}

};


int main()

{

int arr[5] = { 10,20,30,40,50 };


for_each(arr, arr + 5, Functor1());

cout << endl << endl;

for_each(arr, arr + 5, Functor2());

cout << endl << endl;

for_each(arr, arr + 5, Functor3());


return 0;

}

Posted by kimmayer

함수 포인터는 함수의 시작 주소를 저장하는 포인터

함수의 이름은 함수가 시작하는 시작 주소를 나타내며 함수 포인터는 이 함수의 주소를 저장하는 포인터!


#include <iostream>

#include <cstring>

using namespace std;


class Point

{

int x;

int y;

public:

explicit Point(int _x = 0, int _y = 0) :x(_x), y(_y) {}

void Print() const { cout << x << ", " << y << endl; }

void PrintInt(int n) { cout << "테스트정수: "<< n << endl; }

};


int main()

{

Point pt(2, 3);

Point *p = &pt;


void (Point::*pf1)() const; //멤버 함수 포인터 선언

pf1 = &Point::Print;


void(Point::*pf2)(int); //멤버 함수 포인터 선언

pf2 = &Point::PrintInt;


pt.Print();

pt.PrintInt(10);

cout << endl;


(pt.*pf1)();

(pt.*pf2)(10);

cout << endl;


(p->*pf1)();

(p->*pf2)(10);


return 0;

}

'Programing > C++' 카테고리의 다른 글

두 정수가 같으면 true 다르면 false를 리턴하는 Equal 클래스  (0) 2015.09.04
함수 객체  (0) 2015.09.04
형변환 연산자 오버로딩  (0) 2015.09.04
-> , * 연산자 오버로딩  (0) 2015.09.02
간단한 오버라이딩  (0) 2015.09.02
Posted by kimmayer
이전버튼 1 2 3 4 5 6 7 8 ··· 20 이전버튼

블로그 이미지
IT 기술들 정리, 독후감을 주로 남깁니다!
kimmayer

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함