Reputation: 2304
I have two classes, one is the parent of the other. They both need to have different operator<< functions. Each class has an output function that's unique to it. Here's how they are more or less set up:
template <class T>
class Tree {
protected:
T elem;
vector< Tree<T>* > children;
public:
ostream &output(ostream& stream,int level) {
stream << "Tree" << endl;
for (int j=0;j<level;j++) stream << " ";
stream << '\'' << this->elem << '\'' << endl;
for (unsigned int i=0;i<this->children.size();i++) {
this->children[i]->output(stream,level+1);
}
return stream;
}
template <class U>
friend ostream &operator<<(ostream &cout,Tree<U> &obj);
};
template <class T>
ostream &operator<<(ostream &stream,Tree<T> &obj) {
obj.output(stream,0);
return stream;
};
template <class T>
class ParseTree : public Tree<T> {
protected:
ParseTree<T>* elemTree;
vector< ParseTree<T>* > children;
public:
ostream &output(ostream& stream,int level) {
stream << "ParseTree" << endl;
if (elemTree == NULL) {
for (int j=0;j<level;j++) stream << " ";
stream << '\'' << this->elem << '\'' << endl;
}
else {
elemTree->output(stream,level+1);
}
for (unsigned int i=0;i<this->children.size();i++) {
this->children[i]->output(stream,level+1);
}
return stream;
}
template <class U>
friend ostream &operator<<(ostream &cout,ParseTree<U> &obj);
};
template <class T>
ostream &operator<<(ostream &stream,ParseTree<T> &obj) {
obj.output(stream,0);
return stream;
};
Both output functions recursively print out the tree, but ParseTree's is slightly different. The problem I'm having is that when I try to cout << a ParseTree the first iteration is from ParseTree's output function (as confirmed by the stream << "ParseTree" << endl statement), but all subsequent requests seem to be Tree's ouput function (as confirmed by the stream << "Tree" << endl statement). Every object pushed onto the children vector is definitely a ParseTree. My guess is that ParseTree::children is different from Tree::children, and for some reason the context is getting switched. Any ideas?
Upvotes: 0
Views: 723
Reputation: 8143
Make output virtual
and define operator<<
only once with an argument of type Tree<T>
. That should be sufficient.
Upvotes: 2