From: Lukas Jiriste Date: Thu, 17 Oct 2024 08:27:19 +0000 (+0200) Subject: Add solution to ex01 (without Makefile) X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=d1bd17391471e3d13ce98c9fd785b6e28f9d4b20;p=42%2FCPP_Module_02 Add solution to ex01 (without Makefile) --- diff --git a/ex01/Fixed.cpp b/ex01/Fixed.cpp new file mode 100644 index 0000000..8f5ceb4 --- /dev/null +++ b/ex01/Fixed.cpp @@ -0,0 +1,62 @@ +#include "Fixed.h" +#include + +Fixed::Fixed(): m_num(0) +{ + std::cout << "Default constructor called\n"; +} + +Fixed::Fixed(const int init): m_num(init << point_pos) +{ + std::cout << "Int constructor called\n"; +} +Fixed::Fixed(const float init): m_num(init * (1 << point_pos)) +{ + std::cout << "Float constructor called\n"; +} + +Fixed::Fixed(const Fixed &other) +{ + std::cout << "Copy constructor called\n"; + *this = other; +} + +Fixed::~Fixed() +{ + std::cout << "Destructor called\n"; +} + +Fixed &Fixed::operator=(const Fixed &other) +{ + std::cout << "Copy assignment operator called\n"; + if (this == &other) + return (*this); + m_num = other.getRawBits(); + return (*this); +} + +std::ostream &operator<<(std::ostream &ostream, const Fixed &num) +{ + ostream << num.toFloat(); + return (ostream); +} + +int Fixed::getRawBits() const +{ + return (m_num); +} + +void Fixed::setRawBits(int const raw) +{ + m_num = raw; +} + +int Fixed::toInt() const +{ + return (m_num >> point_pos); +} + +float Fixed::toFloat() const +{ + return (static_cast(m_num) / (1 << point_pos)); +} diff --git a/ex01/Fixed.h b/ex01/Fixed.h new file mode 100644 index 0000000..4e0ad5d --- /dev/null +++ b/ex01/Fixed.h @@ -0,0 +1,29 @@ +#ifndef FIXED_H +# define FIXED_H + +# include + +class Fixed +{ + private: + static const int point_pos = 8; + int m_num; + + public: + Fixed(); + Fixed(const int init); + Fixed(const float init); + Fixed(const Fixed &other); + ~Fixed(); + + Fixed &operator=(const Fixed &other); + + int getRawBits() const; + void setRawBits(int const raw); + float toFloat() const; + int toInt() const; +}; + +std::ostream &operator<<(std::ostream &ostream, const Fixed &num); + +#endif // FIXED_H