templates and operator overloading
Apr 14, 2010 at 12:49pm UTC
What am I doing wrong? Here is some code:
friend ostream& operator << <>(ostream& os, const binary_tree<T>& bt);
1 2 3 4 5 6
template <class T>
ostream& operator <<(ostream& os, const binary_tree<T>& bt)
{
_print(os,bt.root);
return os;
}
Here is the error output:
|error: `_print' was not declared in this scope|
I did this to fix it.. but can it be done without the temp?
I think I made some big mistakes somewhere...Not very used to working with templates.
1 2 3 4 5 6 7
template <class T>
ostream& operator <<(ostream& os, const binary_tree<T>& bt)
{
binary_tree<T> temp;
temp._print(os,bt.root);
return os;
}
L.E:
This can't be right... cause it's not as efficient as using the print() function it the class, since it has to make a clone of the object I want to print, which is O(n), and another O(n) to print it. That can't be right.. why can't I make:
1 2 3 4 5 6
template <class T>
ostream& operator <<(ostream& os, const binary_tree<T>& bt)
{
bt._print(os,bt.root);
return os;
}
Even later edit:
This way it works.. though why? It's not like the function _print() modifies anything..
1 2 3 4 5 6
template <class T>
ostream& operator <<(ostream& os, binary_tree<T>& bt)
{
bt._print(os,bt.root);
return os;
}
Here is the _print() function:
template<class T>
1 2 3 4 5 6 7
void binary_tree<T>::_print(ostream& os, node* tree)
{
if (tree==NULL) return ;
_print(os,tree->left);
os << tree->data << ", " ;
_print(os,tree->right);
}
Last edited on Apr 14, 2010 at 1:07pm UTC
Apr 14, 2010 at 1:16pm UTC
On the first code you didn't put
bt.
before
_print
This way it works.. though why? It's not like the function _print() modifies anything..
You need to say this to the compiler:
void binary_tree<T>::_print(ostream& os, node* tree) const
Apr 14, 2010 at 1:50pm UTC
Thanks! It works. Good to know.
Topic archived. No new replies allowed.