#include #include template class triad { protected: T a, b, c; public: triad(T x, T y, T z) { a = x; b = y; c = z; } T geta() const { return a; } T getb() const { return b; } T getc() const { return c; } T & operator[](int i) // x[3] --> x.operator[](3) // doesn't have to be int { if (i == 1) return a; else if (i == 2) return b; else if (i == 3) return c; cout << "error in index\n"; } T getsmallest() { if (a < b) { if (a < c) return a; else return c; } else { if (b < c) return b; else return c; } } T getbiggest() { if (a > b) { if (a > c) return a; else return c; } else { if (b > c) return b; else return c; } } void print() { cout << "<" << a << ", " << b << ", " << c << ">"; } }; /* original triad add(triad x, triad y) { int ra = x.geta() + y.geta(); int rb = x.getb() + y.getb(); int rc = x.getc() + y.getc(); return triad(ra, rb, rc); } */ template triad operator+(triad x, triad y) { what ra = x.geta() + y.geta(); what rb = x.getb() + y.getb(); what rc = x.getc() + y.getc(); return triad(ra, rb, rc); } template ostream & operator<<(ostream & os, const triad & x) { os << "<"; os << x.geta(); os << ", "; os << x.getb(); os << ", "; os << x.getc(); os << ">"; return os; } typedef string note; typedef triad chord; typedef triad point; void main() { chord cmaj("C", "E", "G"); triad zoo("lion", "tiger", "bear"); point p1(12, 6, 9); cout << "smallest in zoo: " << zoo.getsmallest() << "\n"; cout << "cmaj = "; cmaj.print(); cout << "\n"; cout << "p1 = "; p1.print(); cout << "\n\n\n"; triad cat(4, 5, 6); triad dog(5, 2, 4); triad sum = cat + dog; cout << cat << " + " << dog << " = " << sum << "\n"; zoo.print(); cout << " + "; cout << " becomes "; triad sum2 = zoo + triad("-leo", "-tim", "-belinda"); sum2.print(); cout << "\n\n\n"; (zoo + cmaj).print(); cout << "\n\n"; for (int i = 1; i <= 3; i += 1) cout << " " << zoo[i]; cout << "\n\n"; zoo[2] = "anteater"; // this is why operator[] must return a reference for (int i = 1; i <= 3; i += 1) cout << " " << zoo[i]; cout << "\n\n"; }