This is an exercise to create a class that behaves exactly like an int
.
Questions
- Am I missing anything?
- Or did I going about this about this the wrong way?
- Is there anything I could improve on?
- Are there any tricks that I could learn from this?
- How about style; does the style look OK?
#include <iostream> // std::cout
#include <utility> // std::move
class jd_int {
public:
jd_int() = default;
jd_int(int i) : _i{i} { }
jd_int(const jd_int& jdi) : _i{jdi._i} { }
jd_int(jd_int&& jdi) : _i{std::move(jdi._i)} { }
jd_int operator= (int i) { _i = i; return *this; }
jd_int operator= (double d) { _i = d; return *this; }
jd_int operator= (const jd_int& jdi) { _i = jdi._i; return *this; }
jd_int operator= (jd_int&& jdi) { _i = std::move(jdi._i); return *this; }
~jd_int() = default;
operator bool() { return !!_i; }
operator int() { return static_cast<int>(_i); }
operator double() { return static_cast<double>(_i); }
jd_int operator+=(jd_int jdi) { return _i += jdi._i; }
jd_int operator+ (jd_int jdi) { return _i + jdi._i; }
jd_int operator-=(jd_int jdi) { return _i -= jdi._i; }
jd_int operator- (jd_int jdi) { return _i - jdi._i; }
jd_int operator*=(jd_int jdi) { return _i *= jdi._i; }
jd_int operator* (jd_int jdi) { return _i * jdi._i; }
jd_int operator/=(jd_int jdi) { return _i /= jdi._i; }
jd_int operator/ (jd_int jdi) { return _i / jdi._i; }
jd_int operator%=(jd_int jdi) { return _i %= jdi._i; }
jd_int operator% (jd_int jdi) { return _i % jdi._i; }
jd_int operator++() { return ++_i; }
jd_int operator++(int) { jd_int tmp = *this; ++_i; return tmp; }
jd_int operator--() { return --_i; }
jd_int operator--(int) { jd_int tmp = *this; --_i; return tmp; }
friend bool operator< (jd_int lhs, jd_int rhs);
friend bool operator> (jd_int lhs, jd_int rhs);
friend bool operator<=(jd_int lhs, jd_int rhs);
friend bool operator>=(jd_int lhs, jd_int rhs);
friend bool operator==(jd_int lhs, jd_int rhs);
friend bool operator!=(jd_int lhs, jd_int rhs);
private:
int _i;
friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);
friend std::istream& operator>>(std::istream& is, jd_int jdi);
};
bool operator< (jd_int lhs, jd_int rhs) { return (lhs._i < rhs._i); }
bool operator> (jd_int lhs, jd_int rhs) { return (lhs._i > rhs._i); }
bool operator<=(jd_int lhs, jd_int rhs) { return (lhs._i <= rhs._i); }
bool operator>=(jd_int lhs, jd_int rhs) { return (lhs._i >= rhs._i); }
bool operator==(jd_int lhs, jd_int rhs) { return (lhs._i == rhs._i); }
bool operator!=(jd_int lhs, jd_int rhs) { return (lhs._i != rhs._i); }
std::ostream& operator<<(std::ostream& os, const jd_int jdi) {
os << jdi._i;
return os;
}
std::istream& operator>>(std::istream& is, jd_int jdi) {
is >> jdi._i;
return is;
}
```
int
by comparing against an actualint
. That's not simulating, that's wrapping. \$\endgroup\$ – Mast Apr 29 '19 at 6:44