-
Overloaded << operator
Quick question. If I have a method to overload the << operator:
Header:
Code:
ostream& operator <<(ostream &os, const Set &s);
In the cpp:
Code:
ostream& operator <<(ostream &os, const Set &s)
{
//print to a file
}
Is this the correct way to do this? I have checked around and it says it's the right way to do it but I am still getting errors.
-
Yes it is the correct way. If you'd tell what errors you get, we might even be able to tell you why.
Kurt
-
I get "In file included from Set.cpp"
"expected constructor, destructor, or type conversion before '&' token"
"expected `,' or `;' before '&' token"
What do I have to include?
-
could be <iostream> or the header that declares Set.
Kurt
-
The program works fine just before I included the 2 code snippets from above. I had it printing with cout and I just wanted to get the overloading code right before I actually used it in my driver.
-
I still think it should be
Code:
#include <iostream>
using std::ostream;
in Set.h
Kurt
-
Thank you so much! That works. :D
-
Hate to bother you again, but is there any easy explanation for why it gives the error "undefined reference to 'Set::displaySet()'" when i declare that method as a const. It works when it isn't const.
-
I get this error when I forget to add the const in the implementation.
Kurt
-
Hmm.
Code:
void displaySet() const;
Code:
void Set::displaySet() const
{
cout << "{";
for(int i=1;i<=myList.getLength();i++)
{
cout<<getValue(i);
if(i!=myList.getLength())
cout<<",";
}
cout << "}";
}
I changed both to const. I don't have to do anything differently when I use it throughout my cpp file do I?
-
Don't think so. What's the problem ?
Kurt
-
I changed displaySet to const in both the .h and .cpp and now it gives me the error "undefined reference to 'Set::displaySet()'". :(
-
Don't understand why. Have you rebuilt the whole project.
Kurt
-
You really are my hero. It worked.
-
Happens quite often. Most of the IDE's are not smart enough to check headers for dependancies.
Kurt