ostream as argument & overloading an operator

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?

Last edited on
I tried defining it as void print(ostream str, int indent = 0)

You're on the right track. You need to pass ostream by reference.
 
void node::print (ostream & os, int indent)


Overloading the << operator is easy once you get the hang of it.
1
2
3
4
5
//  inside your node class declaration:
  friend ostream & operator << (ostream & os, const node & n)
  {  n.print (os, 0);
      return os;
  }

Must be a friend so that the overloaded function has access to members of node (print).
Must return a reference to the stream.
Takes a stream and a node, both by reference.
node should be passed as a const reference. This implies that node::print is a const function.

You won't be able to use the overloaded << operator to print indented nodes since the overloaded operator expects exactly two arguments. No way to pass the indent value.
node::print can still call itself to print indented nodes as you're doing at line 26.

One point of optimization: No need to concatenate spaces onto a string. Just output the spaces directly.
15
16
17
18
       // create indentation
	for (int i = 0; i < indent; i++) 
        {  os << ' '; 
	}
Last edited on
Thanks, works perfectly fine. :)
Topic archived. No new replies allowed.