-
20141029 (C++ ()연산자와 Functor(펑터), ARM SAM-BA)부산IT학원/스마트컨트롤러 2014. 10. 30. 10:52
168일차
--------
C++
--------
------- 연산자 ()와 Functor(펑터)
객체를 함수처럼 사용하는 것을 말한다.
다음 예제로 확인
예제)
#include <iostream>
using namespace std;
class Point
{
private:
int xpos;
int ypos;
public:
Point(int x = 0, int y = 0) : xpos(x), ypos(y)
{ }
Point operator+(const Point& pos) const
{
return Point(xpos + pos.xpos, ypos + pos.ypos);
}
friend ostream& operator<<(ostream& os, const Point& pos);
};
ostream& operator<<(ostream& os, const Point& pos)
{
cout << "[" << pos.xpos << ", " << pos.ypos << "]" << endl;
return os;
}
class Adder
{
public:
int operator()(const int& n1, const int& n2)
{
return n1 + n2;
}
double operator()(const double& n1, const double& n2)
{
return n1 + n2;
}
Point operator()(const Point& n1, const Point& n2)
{
return n1 + n2;
}
};
int main()
{
Adder adder;
cout << adder(1, 3) << endl;
cout << adder(1.5, 1.7) << endl;
cout << adder(Point(3,4), Point(7, 7));
return 0;
}
객체를 함수처럼 사용하는 것을 Functor라고 부른다.
또 다른 예제
예제)
#include <iostream>
using namespace std;
class SortRule // 추상 클래스
{
public:
virtual bool operator()(int num1, int num2) const = 0; // 순수 가상함수
};
class AscendingSort : public SortRule
{
public:
bool operator()(int num1, int num2) const
{
if(num1 > num2)
return true;
else
return false;
}
};
class DescendingSort : public SortRule
{
public:
bool operator()(int num1, int num2) const
{
if(num1 < num2)
return true;
else
return false;
}
};
class DataStorage
{
private:
int * arr;
int idx;
const int MAX_LEN;
public:
DataStorage(int arrlen) : idx(0), MAX_LEN(arrlen)
{
arr = new int[MAX_LEN];
}
void AddData(int num)
{
if(MAX_LEN <= idx)
{
cout << "더 이상 저장이 불가능합니다." << endl;
return;
}
arr[idx++] = num;
}
void ShowAllData()
{
for(int i= 0; i < idx; ++i)
{
cout << arr[i] << " ";
}
cout << endl;
}
void SortData(const SortRule& functor)
{
for(int i = 0; i < (idx - 1); ++i)
{
for(int j = 0; j < (idx - 1); ++j)
{
if(functor(arr[j], arr[j+1]))
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
};
int main()
{
DataStorage storage(5);
storage.AddData(40);
storage.AddData(30);
storage.AddData(50);
storage.AddData(20);
storage.AddData(10);
storage.SortData(AscendingSort());
storage.ShowAllData();
storage.SortData(DescendingSort());
storage.ShowAllData();
return 0;
}
결과
이렇게 사용한다.
-------------
ARM
-------------
------- SAM-BA
ARM에 프로그램을 올려줄 때 SAM-BA를 사용한다.
현재 실습용 장비인데,
항상 프로그램을 넣어주기 전에 TST를 켜고 POWER을 켜서
안에 프로그램을 지워주고, PC와 연결하여 프로그램을 넣었다.
그 구동 원리는
(Memory)
칩 내부에 SAM-BA 프로그램이 저장되어 있어,
TST를 켜면 SAM-BA 프로그램이 Flash에 저장되고,
Windows와 통신이 가능하게 되면서 프로그램을 넣을 수 있게 되는 것이었다.
'부산IT학원 > 스마트컨트롤러' 카테고리의 다른 글
20141031 (C++ Template 분할 컴파일, ARM PWM) (0) 2014.10.31 20141030 (C++ string class, Template) (0) 2014.10.30 20141028 (C++ new, delete, *, -> 연산자 오버로딩, ARM 소스변환) (0) 2014.10.28 20141027 (C++ 객체 초기화, 대입연산자, 배열 연산자, ARM ADS) (0) 2014.10.27 20141015 (C++ class 내에 const static, mutable, 상속, ) (0) 2014.10.15