So I am practicing CLASSES and here I have this "cannot overload functions distinguished by return type alone" underlining my "operator". How do solve this so I can use cout << in my main()
Note that #include <iostream> is in the BOOK.cpp.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#ifndef BOOK_H
#define BOOK_H
class BOOK
{
public:
string title;
string author;
int pages;
BOOK();
friend ostream& operator<<(ostream& os, const BOOK& book1);
};
ostream& operator<<(ostream& os, const BOOK& book1);
#endif
@jlb, actually I followed suit and left it in both places without thinking! I agree it's best outside if the members are really public, but if they're made private then maybe an inline in-class friend definition if it's quite short. Possibly no need for a separate cpp (and object) file if the whole class is simple.
But he doesn't need fstream I don't think. Just iostream (or even just ostream), plus string, of course.
But he doesn't need fstream I don't think. Just iostream (or even just ostream), plus string, of course.
Actually he doesn't need iostream, just fstream and string, in fact he could use <ostream> instead. The iostream header brings in much more than fstream or ostream than is required.
actually I followed suit and left it in both places without thinking!
Remember that you can only have one definition, not two. How is the compiler going to know, when you implement the function what definition you're trying to implement, remember the function implementation doesn't contain the "friend" information.
I agree it's best outside if the members are really public, but if they're made private then maybe an inline in-class friend definition
The reason for a "friend" is so the function can access the private members of the class, since there are no private members then the "friend" is not needed. If the members are private (or protected) then you either need a "friend" or public member functions to access the class internals.
You're not making any sense. If you're so worried about bringing too much then why use fstream instead of ostream? Anyway, I mentioned ostream in my previous post. And there's certainly no harm including iostream.
Thanks for the pointless lessons about the one definition rule and friend functions. Duh.