Calling operator<<?

My program is telling me my Book class doesn't have an operator<< function even though it does. I'm trying to call it from my BST program. I did #include the Book.h file in both my BST.h and BST.cpp files.

Here it is in my Book.h file:
1
2
3
4
5
6
7
8
9
10
11
  #include <string>
#ifndef Book_Header
#define Book_Header

class Book
{
public:
friend std::ostream& operator<<(std::ostream& os, Book& b);
}

std::ostream& operator<<(std::ostream& os, Book& b);


Here's me calling it in my BST.cpp file. Did I call it incorrectly?

1
2
3
4
5
6
7
8
9
10
11
std::ostream &operator<<(std::ostream& os, BST& rhs)
{
	while (rhs.root != NULL)
	{
		Book::operator<<(os, rhs.root->left);
		return os << rhs.root->bookNode;
		Book::operator<<(os, rhs.root->right);
	}
	
};


What is the type of rhs.root->left and rhs.root->right ?
Book doesn't have a operator<<.
You have a global function, called operator<< that receives an ostream and a Book, and that has access to the privates of the Book.
Which I think that you are calling correctly in line 6.

The error probably point you to lines 5 and 7, where I suspect you are trying to make a recursive call.
Sorry, here's the typing of the entire struct in BST.h:

1
2
3
4
5
6
7
8
9
10
11
12
class BST
{
private:
	struct Node
	{
		Node *left;
		Node *right;
		Book bookNode;
	};

	Node *root;
	Node *current;


@ne555 Yeah, the errors are on lines 5 and 7 and I'm trying to call it recursively. I just don't know how to call what I need using the operator<< in Book.h.
The os and rhs.root->bookNode are std::ostream and Book, respectively, but on the erroneous lines you are calling

std::ostream & Book::operator<<( std::ostream&, Node* )

That obviously fails, for Book has no member operator<< of any kind.

Besides, operators are usually called with the other syntax:
os << rhs.root->left << rhs.root->bookNode << rhs.root->right;


Make a standard standalone recursive function that takes ( std::ostream&, Node* ) and then call it from the operator<<( std::ostream&, BST& ).

Speaking of that operator:
* When does the loop end? The condition on line 3 should not change within the loop.
* Line 7 is never executed due to the return on line 6.


PS. Don't you ever have const Books or BST's to print? Surely the "print" operation does not modify the printed object?
It won't let me make the function that takes ( std::ostream&, Node* ) because it says that Node is undefined in my header file since I have to declare operators outside the standard class, even if I make it a friend.
Use BST::Node to refer to the Node class outside of the BST class.
Got it. Thanks for the help, guys!
Topic archived. No new replies allowed.