Fixed.cpp
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* Fixed.cpp :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: gychoi <gychoi@student.42seoul.kr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2023/08/02 17:46:11 by gychoi #+# #+# */ 9 /* Updated: 2023/08/04 17:19:15 by gychoi ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include <cmath> 14 #include "Fixed.hpp" 15 16 Fixed::Fixed(void) : _rawBits(0) 17 { 18 std::cout << "Default constructor called" << std::endl; 19 } 20 21 Fixed::Fixed(Fixed const& fixed) 22 { 23 std::cout << "Copy constructor called" << std::endl; 24 _rawBits = fixed.getRawBits(); 25 } 26 27 Fixed::Fixed(int const intValue) 28 { 29 std::cout << "Int constructor called" << std::endl; 30 _rawBits = intValue << _fractionalBits; 31 } 32 33 Fixed::Fixed(float const floatValue) 34 { 35 std::cout << "Float constructor called" << std::endl; 36 _rawBits = static_cast<int>(roundf(floatValue * (1 << _fractionalBits))); 37 } 38 39 Fixed& Fixed::operator=(Fixed const& fixed) 40 { 41 std::cout << "Copy assignment operator called" << std::endl; 42 if (this != &fixed) 43 setRawBits(fixed.getRawBits()); 44 return (*this); 45 } 46 47 Fixed::~Fixed(void) 48 { 49 std::cout << "Destructor called" << std::endl; 50 } 51 52 int Fixed::getRawBits(void) const 53 { 54 return (_rawBits); 55 } 56 57 void Fixed::setRawBits(int const raw) 58 { 59 _rawBits = raw; 60 } 61 62 int Fixed::toInt(void) const 63 { 64 return (_rawBits / (1 <<_fractionalBits)); 65 } 66 67 float Fixed::toFloat(void) const 68 { 69 return (static_cast<float>(_rawBits) / (1 << _fractionalBits)); 70 } 71 72 std::ostream& operator<<(std::ostream& os, Fixed const& fixed) 73 { 74 os << fixed.toFloat(); 75 return (os); 76 }