2가지 방법
1) 전역 함수로 구현
예시
선언 (hpp)
void operator + (const Fixed & f1, const Fixed & f2);
정의(cpp)
void operator + (const Fixed & f1, const Fixed & f2)
{
std::cout << f1.toFloat() + f1.toFloat() << std::endl;
}
> hpp 파일의 Fixed class에서 public에다 연산자 오버로딩 선언을
> ```cpp
> friend void operator + (const Fixed & f1, const Fixed & f2);
> ```
> 이렇게 하면, 연산자 오버로딩함수에서 private 변수를 가져다 사용할 수 있게된다.
사용
Fixed ff1(10);
Fixed ff2(20);
ff1 + ff2;
결과
30
출력2) 멤버 함수로 구현
예시
선언(hpp)
class Fixed
{
private:
int _fixedPointNum;
static const int _fractionalBits = 8;
public:
Fixed();
~Fixed();
void& operator + (const Fixed &source);
}
정의(cpp)
void Fixed::operator + (const Fixed &source)
{
std::cout << this->_fixedPointNum + source._fixedPointNum << std::endl;
}
사용
Fixed ff1(10);
Fixed ff2(20);
ff1 + ff2;
결과
30
출력