Add solution to ex01 (without Makefile)
authorLukas Jiriste <ljiriste@student.42prague.com>
Thu, 17 Oct 2024 08:27:19 +0000 (10:27 +0200)
committerLukas Jiriste <ljiriste@student.42prague.com>
Thu, 17 Oct 2024 11:51:38 +0000 (13:51 +0200)
ex01/Fixed.cpp [new file with mode: 0644]
ex01/Fixed.h [new file with mode: 0644]

diff --git a/ex01/Fixed.cpp b/ex01/Fixed.cpp
new file mode 100644 (file)
index 0000000..8f5ceb4
--- /dev/null
@@ -0,0 +1,62 @@
+#include "Fixed.h"
+#include <iostream>
+
+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<float>(m_num) / (1 << point_pos));
+}
diff --git a/ex01/Fixed.h b/ex01/Fixed.h
new file mode 100644 (file)
index 0000000..4e0ad5d
--- /dev/null
@@ -0,0 +1,29 @@
+#ifndef FIXED_H
+# define FIXED_H
+
+# include <iostream>
+
+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