First of all, sorry for putting 2 questions in one topic, but I feel like they belong together in this case.
I implemented a basic tree structure. It has a
print()
function, defined as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
// node.h
using namespace std;
class node {
public:
void print(int indent = 0);
...
}
// node.cpp
using namespace std;
void node::print(int indent) {
// create indentation
string space = "";
for (int i = 0; i < indent; i++) {
space += " ";
}
// print out name
string name = this->get_name();
cout << space << name << endl;
// call print() on all children with 4 more spaces indentation
for (int i = 0; i < this->get_nr_children(); i++) {
this->get_child(i)->print(indent + 4);
}
}
|
So far it works fine, but I need this function to take any ostream and not just cout. I tried defining it as
void print(ostream str, int indent = 0)
and chanding the relevant definition line to
str << space << name << endl;
. I don't really know how else to do this...
Next I need to overload the << operator so that
std::cout << node
calls
node->print()
. I have seen several pages, explaining how overloading works but I didn't really understand them comletely. My first question would be: Do I implement it as a member function or not? What fits my case?
And the second of course, how do I implement function overloading?