Overloading the stream insertion operator - c++

I am trying to overload the stream insertion operator for an assignment. In my header file, I have the following:
friend ostream& operator<<(ostream, Vector);
In my implementation file, I have:
friend ostream& operator<<(ostream& outputStream, Vector& displayMe) {
outputStream << "<" << displayMe.GetVX << "," << displayMe.GetVY << ">";
return outputStream;
}
I am getting an error that says:
"invalid specifier outside a class declaration"
The error is pointing to the line that begins with friend ostream& in my implementation file.
I am new to operator overloading obviously. Am I supposed to define this outside of the class? I am just confused about why I am getting this error and how I go about fixing my code. Any suggestions would be helpful.

You need to declare the ostream<< operator within the Vector class:
class Vector
{
// ...
friend ostream& operator<<(ostream&, Vector&);
};
Notice also that you need to use references in the signature as well.
You don't specify friend in the implementation of the operator.
Also, it's advisable to take the Vector by const-reference here:
ostream& operator<<(ostream&, Vector const&);

Related

Overloading insertion << operator

Hello I am trying to overload the insertion operator but there is an error in my compiler when initializing it.
In the .h file
class Zfraction{
public:
friend std::ostream& operator<<(std::ostream& display, Zfraction const& b);
}
in the .cpp
std::ostream& Zfraction::operator<<(std::ostream &display, Zfraction const& b){
}
There is the output
Overloaded 'operator<<' must be a binary operator (has 3 parameters)
Do you have any idea ?
The header in the .cpp file is wrong. By using the scope resolution operator, ::, you're indicating that the operator that you're overloading is a member function of the Zfraction class. This is not true. Although friend declarations must take place inside of the class that they are establishing friendship with, they are not member functions (in other words, they don't have access to a *this pointer). Thus, you need to change the .cpp file to the following:
std::ostream& operator<<(std::ostream &display, Zfraction const& b){
/* Provide your implementation here. */
}

Type conversion in ostream& operator <<

I have a class entry and an ostream& operator << overwritten for it. I also have an auxiliary class cursor and a type conversion operator entry().
Then, in my main() function I have the following expression:
cout << data[4];
where data[4] is a cursor, but compilation fails with
error: invalid operands to binary expression
What I want is for a compiler to convert data[4] to entry and to use its << operator.
Is there any way to call this ostream operator in an aforementioned way without having to add special methods to entry?
Here are some pieces of code:
class entry
{
friend class cursor;
/*here comes some data*/
public:
friend ostream& operator << (ostream& out, const entry& a);
};
class cursor
{
database* data_;
size_t ind_;
friend class entry;
friend class database;
public:
cursor (database* a, size_t ind);
cursor (const cursor& a);
void operator= (const entry x);
void operator= (const cursor a);
operator entry(); //type conversion
};
and here is what I use in main():
cout << data[4];
When you write:
class entry
{
// ...
friend ostream& operator << (ostream& out, const entry& a);
};
Although this declares operator<< in the enclosing scope, the name lookup rules say that name lookup in that scope does not actually find this function! (Because it has only been declared via friend).
If a function has only been declared via friend, then the only way it can be found is via argument-dependent lookup. See this thread for more detailed explanation of the lookup rules.
The function would be found by:
entry e;
cout << e;
because ADL sees that there is an argument of type entry and so it searches functions that are associated with entry (including friends declared there).
However, cursor c; cout << c; does not include entry in its search list (even though a conversion from cursor to entry exists).
To fix this you need to provide a non-friend declaration of the operator, that is visible at the point of main. For example:
ostream& operator << (ostream& out, const class entry& a);
class entry
{
// ...
friend ostream& operator << (ostream& out, const entry& a);
};
NB. I chose to put the declaration before the class instead of after, because this is also the best way to solve the template friends problem.

Templates Objects and Primitives

I have the following class template which will accept both primitives and object. However like this I can only print primitives. How can I make it function using both primitives and objects? Thanks
template<class T>
class A
{
private:
vector <T> l;
public:
void print() const
{
for (int i=0;i<.size();i++)
{
cout<<l[i]<<endl; //error here
}
}
};
The reason why you can print primitives is that <iostream> provides overloads for operator<< for them.
To let your template print your classes in the same way, you need to define your own implementation of the operator:
// This implementation puts operator << outside your class.
// Mark it "friend" in MyClass if it needs access to private members of MyClass.
ostream& operator<<(ostream& ostr, const MyClass& myClass) {
// Do the printing based on the members of your class
ostr << myClass.member1 << ":" << myClass.member2;
return ostr;
}
The compiler will detect this operator during template expansion, and use it for printing when you do this:
cout<<l[i]<<endl;
You can put operator<< inside your class as well:
ostream &operator<<(ostream &os) {
ostr << member1 << ":" << member2;
}
I am assuming that here, you want to print an object instead of a variable belonging to a fundamental datatype.
For such cases, you can look at operator overloading in C++(more specifically overloading insertion operator).
For more information about overloading the insertion operator for an object, you can visit this URL
http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
Given below is an example about how to go about it
ostream& operator<<(ostream& os, const Datatype& dt)
{
os << dt.a <<" " << dt.b;
return os;
}
Here Datatype is the name of the class and a and b are two private members of a and b which will be printed when you try to print the object.
However, to overload using this technique, do not forget to make this function as a friend function of the class(as given below) as the function requires access the to private members of the class.
friend ostream& operator<<(ostream& os, const Datatype& dt);

Can ostream overloading be a function member?

I have a class Counter and I want to overload operator << to output the data member of Counter. I tried to make the ostream overloading a member function:
Counter{
public:
std::ostream& operator<<(std::ostream& outStream, const Counter& c);
private:
int count_;
};
std::ostream& Counter::operator<<(std::ostream& outStream, const Counter& c){
outStream << c.count_;
return outStream;
}
But the g++ compiler always outputs the same error:
‘std::ostream& Counter::operator<<(std::ostream&, const Counter&)’ must take exactly one argument
However, if I changed the overloading function to be a friend of the class, it worked all well, like this:
Counter{
public:
friend std::ostream& operator<<(std::ostream& outStream, const Counter& c);
private:
int count_;
};
std::ostream& operator<<(std::ostream& outStream, const Counter& c){
outStream << c.count_;
return outStream;
}
Does this mean that the the stream operator overloading cannot be a member function of a class?
Add a public query method that returns the value of count_, then it does not have to be a friend:
Counter{
public:
int count() const { return count_; }
private:
int count_;
};
std::ostream& operator<<(std::ostream& outStream, const Counter& c){
outStream << c.count();
return outStream;
}
If you put the ostream operator in the class itself then it will not work the way you expect it to. It would be a member function meaning to invoke it one would have to do this: c.operator<<("output") which is obviously not what you mean to do. For it to work as you expect an ostream operator it must be outside the class. You can do this by making it a friend or just put it outside of the class and use getters (accessors) to output the data.
It doesn't have to be a friend, but it can't be a member. Member operators only work when they are inside the class which corresponds to the left-hand operand.
Unfortunately the useful overloads for the streaming output operators ( << ) cannot be class members, because the ostream& must be on the left in use and declaration. They do not need to be friends of the class you wish to stream unless they need access to protected or private members. This means that if you can implement a streaming operator using just public functions such as observers/accessors without declaring it a friend.
In your first Counter class you are declaring a member function of the class that does not seem valid. In the second example of the Counter class you are stating that your operator overload for << , which seems valid, has access to the private members. In the second example the function must still be declared outside the class.
Wikipedia Operators in C and C++ has a good list of possible operator overloads, including the in class << overloads even though they are not very useful. The in class overloads must be called backwards CounterInstance << cout; which is counterintuitive.

Stream Insertion Operator overloading

Im really unsure how to call the function:
friend ostream& operator<<(ostream& out, stack::myItem& theItem);
that is public to my stack object:
class stack
{
public:
stack(int capacity);
~stack(void);
void method1();
...
private:
struct myItem
{
int item;
};
...
public:
friend ostream& operator<<(ostream& out, stack& s);
friend ostream& operator<<(ostream& out, stack::myItem& theItem);
};
It's no different than using stream operator << for any other type (it is called operator overloading for a reason).
However, outputting should not modify an object, hence you really should pass it by const reference (otherwise calls with temporaries would fail to compile).
friend ostream& operator<<(ostream& out, const stack& s);
friend ostream& operator<<(ostream& out, const stack::myItem& theItem);
This operator is a classic binary operator.
// Say I have an operator declared like this:
return_type operator#(left_type lhs, right_type rhs);
// Then the invocation is done this way:
left_type L;
right_type R;
return_type result = L # R;
In the case of the streaming operator, it is a bit special since the left hand argument and the return type actually have the same type (and indeed, will refer to the same object, albeit at different times). This has been done to allow chaining.
// Chaining
std::cout << "<Output> " << 1 << std::endl;
// Which can be analyzed like such
operator<<(
operator<<(
operator<<(
std::cout ,
"<Output> "
),
1
),
std::endl
);
As you can see, the syntax merely allows a convenient invocation. One might note that the order is very well defined, it is a strict left to right evaluation.
So with your object, it would become:
stack s;
std::cout << s << std::endl;
Just like that!
Call it from where? As it's coded only the class knows about the private struct. No code external to the class could use that method since it couldn't create an instance of the struct. Marking it as friend doesn't do you much good.