Printable.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #ifndef PRINTABLE_H_ #define PRINTABLE_H_ #include <string> #include <iostream> using namespace std; template < class T> class Printable { public : virtual string toString() = 0; friend ostream& operator<<(ostream& os, T t) { os << t.toString(); os.flush(); return os; } }; #endif /* PRINTABLE_H_ */ |
Hello.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #ifndef HELLO_H_ #define HELLO_H_ #include "Printable.h" class Hello : public Printable<Hello> { public : Hello(); Hello(string message); virtual ~Hello(); string toString(); private : string message; }; #endif /* HELLO_H_ */ |
Hello.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <string> #include "Hello.h" using namespace std; Hello::Hello() : message( "Hello World!" ) { } Hello::Hello(string message) : message(message) { } Hello::~Hello() { } string Hello::toString() { return "[Hello] message=" + this ->message; } |
Main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include "Hello.h" using namespace std; int main() { Hello hello; cout << hello << endl; Hello anotherHello( "Hi World!" ); cout << anotherHello << endl; return 0; } |