Operator overloading >>
If you want to define an operator so that you can:
cin >> myGraph
cout << myGraph
You need to do something like this example below:
struct Entry
{
string symbol;
string original;
string currency;
Entry() {}
~Entry() {}
Entry(string& symbol, string& original, string& currency)
: symbol(symbol), original(original), currency(currency)
{}
Entry(const Entry& e)
: symbol(e.symbol), original(e.original), currency(e.currency)
{}
};
istream& operator>>(istream& is, Entry& en);
ostream& operator<<(ostream& os, const Entry& en);
Then do the operations:
istream& operator>>(istream& is, Entry& en)
{
is >> en.symbol;
is >> en.original;
is >> en.currency;
return is;
}
ostream& operator<<(ostream& os, const Entry& en)
{
os << en.symbol << " " << en.original << " " << en.currency;
return os;
}
Note: In this case, Entry is a structure, so the members are public. If you don't want to post them, you can define operator methods as friends so that they can access the private members of the Entry.
Here's what the post would look like if its members weren't public:
struct Entry
{
private:
string symbol;
string original;
string currency;
public:
Entry() {}
~Entry() {}
Entry(string& symbol, string& original, string& currency)
: symbol(symbol), original(original), currency(currency)
{}
Entry(const Entry& e)
: symbol(e.symbol), original(e.original), currency(e.currency)
{}
friend istream& operator>>(istream& is, Entry& en);
friend ostream& operator<<(ostream& os, const Entry& en);
};
a source to share
Graph myGraph;
myGraph >> "bla";
Note that yours is a strange use operator>>()
. It is commonly used as follows:
NumericObject NumericObject::operator>>(NumericObject const& operand) const;
// bitshifts to the right
and
std::istream& operator>>(istream& in, StreamableObject& obj);
// parses a string representation of obj
I guess what you are actually trying to do is write code like this:
cin >> myGraph;
cout << myGraph;
Note that the graph object is not actually the object calling its method.
In this case, what you really want to do is overload the global operator -> functions:
std::istream& operator>> (std::istream&, graph&);
std::ostream& operator<< (std::ostream&, const graph&);
a source to share
If you're new to this, you've picked a rather interesting (read as "tricky") problem to try to solve.
Operator overloads are not exactly functions. They are called indirectly when the compiler tries to resolve code that looks something like this:
Graph g = new Graph();
g >> "do something";
I recommend that you DO NOT do this. Operator overloading can lead to VERY difficult errors to troubleshoot due to side effects. They are also hard on whoever has to maintain your code (which might be for you after you forget why you did it).
Use operator overloads only when their meaning and use are intuitive.
a source to share