Created
March 20, 2021 12:43
-
-
Save grayed/139b04855a7758d6de7c58f8af17d46b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <array> | |
#include <exception> | |
#include <iostream> | |
class BaseNumber { | |
public: | |
virtual void print(std::ostream& os) const = 0; | |
}; | |
template<typename T> | |
class Number : public BaseNumber { | |
protected: | |
T n; | |
Number(T n_) : n(n_) { } | |
public: | |
T getValue() const { return n; } | |
virtual void print(std::ostream& os) const { os << n; } | |
}; | |
template<typename T> | |
std::ostream& operator <<(std::ostream& os, const Number<T>& n) { n.print(os); return os; } | |
class NaturalNumber : public Number<int> | |
{ | |
public: | |
NaturalNumber(int n_) : Number<int>(n_) { } | |
virtual void print(std::ostream& os) const { std::cerr << "NaturalNumber::print()"; os << n; } | |
}; | |
class Signed { | |
public: | |
virtual void switchSign() = 0; | |
}; | |
class IntegerNumber : public Number<int>, public Signed | |
{ | |
public: | |
IntegerNumber(int n_) : Number<int>(n_) {} | |
virtual void print(std::ostream& os) const { std::cerr << "IntegerNumber::print()"; os << n; } | |
virtual void switchSign() { n = -n; } | |
}; | |
class RealNumber : public Number<double>, public Signed | |
{ | |
public: | |
RealNumber(double n_) : Number<double>(n_) {} | |
virtual void print(std::ostream& os) const { std::cerr << "RealNumber::print()"; os << n; } | |
virtual void switchSign() { n = -n; } | |
}; | |
template<typename T> | |
Number<T> operator +(const Number<T>& r, const Number<T>& n) { | |
return Number<T>(r.getValue() + n.getValue()); | |
} | |
template<typename T> | |
RealNumber operator +(const RealNumber& r, const Number<T>& n) { | |
return RealNumber(r.getValue() + n.getValue()); | |
} | |
template<typename T> | |
RealNumber operator +(const Number<T>& n, const RealNumber& r) { | |
return RealNumber(r.getValue() + n.getValue()); | |
} | |
IntegerNumber operator +(const IntegerNumber& i, const NaturalNumber& n) { | |
return IntegerNumber(i.getValue() + n.getValue()); | |
} | |
IntegerNumber operator +(const NaturalNumber& n, const IntegerNumber& i) { | |
return IntegerNumber(i.getValue() + n.getValue()); | |
} | |
int main() | |
{ | |
NaturalNumber nn(12); | |
RealNumber rn(4.2); | |
rn.switchSign(); | |
const BaseNumber* pn1 = &nn; | |
const BaseNumber* pn2 = &rn; | |
std::cout << "Natural: " << nn << std::endl; | |
std::cout << "Real: " << rn << std::endl; | |
std::cout << "Sum: " << nn + rn << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment