operator<< overloading [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Operator overloading
I didn't find any thing that could help me in this subject...
I'm trying to over load the << operator, this is my code:
ostream& Complex::operator<<(ostream& out,const Complex& b){
out<<"("<<b.x<<","<<b.y<<")";
return out;
}
this is the declaration in the H file:
ostream& operator<<(ostream& out,const Complex& b);
I get this error:
error: std::ostream& Complex::operator<<(std::ostream&, const Complex&) must take exactly one argument
what and why I'm doing wrong?
thanks

your operator << should be free function, not Complex class member in your case.
If you did your operator << class member, it actually should take one parameter, which should be stream. But then you won't be able to write like
std::cout << complex_number;
but
complex_number << std::cout;
which is equivalent to
complex_number. operator << (std::cout);
It is not common practice, as you can note, that is why operator << usually defined as free function.

class Complex
{
int a, b;
public:
Complex(int m, int d)
{
a = m; b = d;
}
friend ostream& operator<<(ostream& os, const Complex& complex);
};
ostream& operator<<(ostream& os, const Complex& complex)
{
os << complex.a << '+' << complex.b << 'i';
return os;
}
int main()
{
Complex complex(5, 6);
cout << complex;
}
More info here

As noted, the streaming overloads need to to be free functions, defined outside of your class.
Personally, I prefer to stay away from friendship and redirect to a public member function instead:
class Complex
{
public:
std::ostream& output(std::ostream& s) const;
};
std::ostream& operator<< (std::ostream& s, const Complex& c)
{
return c.output(s);
}

Related

Why is there a difference when overloading different operators?

Consider the following code snippet:
class Complex {
double real, im;
public:
Complex(double real, double im) {
this->real = real;
this->im = im;
}
Complex operator + (Complex const& sec) {
Complex ret(real + sec.real, im + sec.im);
return ret;
}
friend ostream& operator<<(ostream& os, const Complex& com);
};
ostream& operator << (ostream& os, const Complex& com) {
os << com.real << " " << com.im << "i";
return os;
}
Why doesn't the operator overloading of + have to be declared as friend as it will also want to access the private variables of the class from outside, similar to when overloading the << operator? At least that's what I thought but apparently this is not the case.
A member function can access all the variables of a class, public or private. You only need friend for functions or classes that aren't part of your class.

C++ operator I/O overloading

I've encountered a strange problem while overloading << operator for a Complex class (The Complex class and overload function are not complete, but the meaning should be the same - BUT if you feel there is missing some important part, just prompt me ;-) ):
class Complex {
float m_fReal;
float m_fImaginary;
public:
Complex();
Complex(float real, float imaginary);
Complex add(Complex) const;
friend std::ostream& operator<<
(std::ostream& out, Complex cComplex);
};
Overload function:
std::ostream& operator<<(std::ostream& out, Complex cComplex) {
out << cComplex.m_fReal << " " << cComplex.m_fImaginary;
return out;
}
Add function:
Complex Complex::add(Complex cComplex) const {
return Complex (m_fReal + cComplex.m_fReal,
m_fImaginary + cComplex.m_fImaginary);
}
Function call in main:
Complex x(1,1), y(2,2);
cout << "x+y=" << x.add(y) << endl;
While the above works, this does not (only parts that differ).
Declaration in Complex class:
friend std::ostream& operator<<
(std::ostream& out, Complex& cComplex);
Definition:
std::ostream& operator<<(std::ostream& out, Complex& cComplex) {
out << cComplex.m_fReal << " " << cComplex.m_fImaginary;
return out;
}
My intention was to pass the Complex class by reference. Can anybody explain to me, what went wrong in this code and why?
You need to accept the object to output by const reference. You're accepting it as a non-const reference to which the return from add cannot be bound.
std::ostream& operator<<(std::ostream& out, const Complex& cComplex) {
This design/behavior is to prevent mistakes where a function expects to mutate the value of a reference parameter, but the reference has been bound to an unnamed temporary object, in other words memory that can't be accessed again, rendering the changes pointless.
Your definition should be
std::ostream& operator<<(std::ostream& out, const Complex& cComplex) {
out << cComplex.m_fReal << " " << cComplex.m_fImaginary;
return out;
}
cComplex needs to be const qualified for you to access its private variables using "."

Return reference to local variable when overloading <<

I am a beginner trying to learn c++ so probably my question is very basic. Consider the following pice of code:
class pounds
{
private:
int m_p;
int m_cents;
public:
pounds(){m_p = 0; m_cents= 0;}
pounds(int p, int cents)
{
m_p = p;
m_cents = cents;
}
friend ostream& operator << (ostream&, pounds&);
friend istream& operator>>(istream&, pounds&);
};
ostream& operator<< (ostream& op, pounds& p)
{
op<<p.m_p<<"and "<<p.m_cents<<endl;
return op;
}
istream& operator>>(istream& ip, pounds& p)
{
ip>>p.m_p>>p.m_cents;
return ip;
}
This compiles and seems to work but I am not returning a reference to a local variable? Thanks in advance.
It's correct, since there are no local variables, there are references, that will be passed, when operators will be called.
And i suggest you to change signature of operator << to
std::ostream& operator << (ostream& os, const pounds& p);
since, p is not modified in function.

Which operator do I have to overload?

Which operator do I have to overload if I want to use sth like this?
MyClass C;
cout<< C;
The output of my class would be string.
if you've to overload operator<< as:
std::ostream& operator<<(std::ostream& out, const MyClass & obj)
{
//use out to print members of obj, or whatever you want to print
return out;
}
If this function needs to access private members of MyClass, then you've to make it friend of MyClass, or alternatively, you can delegate the work to some public function of the class.
For example, suppose you've a point class defined as:
struct point
{
double x;
double y;
double z;
};
Then you can overload operator<< as:
std::ostream& operator<<(std::ostream& out, const point & pt)
{
out << "{" << pt.x <<"," << pt.y <<"," << pt.z << "}";
return out;
}
And you can use it as:
point p1 = {10,20,30};
std::cout << p1 << std::endl;
Output:
{10,20,30}
Online demo : http://ideone.com/zjcYd
Hope that helps.
The stream operator: <<
You should declare it as a friend of your class:
class MyClass
{
//class declaration
//....
friend std::ostream& operator<<(std::ostream& out, const MyClass& mc);
}
std::ostream& operator<<(std::ostream& out, const MyClass& mc)
{
//logic here
}
You should implement operator<< as a free function.

overloading the << operator in c++

hey, i got something that i cannot understand ,there are two types of solutions for overloading this operator 1 is including the friend at the start of the method and the other 1 goes without the friend.
i would very much like if some1 explain whats the difference between them advantages / disadvantages.
for example overloading the operator << in class rational:
class Rational:
{
private: int m_t,m_b;
...
friend ostream& operator<<(ostream& out,const Rational& r) // option 1
{ return out << r.m_t << "/" <<r.m_b;} // continue of option 1
ostream& operator<<(ostream& out,const Rational& r){return r.print();} // option 2
virtual ostream& print(ostream& out) const // continue of option 2
{ //
return out<<m_t << "/" << m_b;
} //
};
i was told that the second option isnt correct , if some1 can correct me about it i would much appriciate it.
thanks in advance.
The short answer: Option #2 actually isn't an option, but a syntax error, because it tries to define a binary operator as a member passing two operands.
The somewhat longer answer: If you make the second operand a free function (not a member of the class), this will work. Which one is preferable depends on the circumstances and your preferences. For starters: The disadvantage of the first is that it allows operator<< to access everything in Rational (including private helper functions), while the disadvantage of the second is that you introduce a function to the class' public API that nobody needs.
operator<< (for ostream) needs to be a free function (since the left-hand argument is a stream, not your class).
The friend keyword makes it a free function (a free function that has access to the private members).
However, if this functionality can be implemented in terms of the public interface, it is better to do so and just use a non-friend free function.
class Rational:
{
private: int m_t,m_b;
public:
...
virtual ostream& print(ostream& out) const
{
return out<<m_t << "/" << m_b;
}
};
ostream& operator<<(ostream& out,const Rational& r)
{
return r.print(out);
}
Consider a function that should output the num and den of Rational:
ostream& operator<<(ostream& out, const Rational& r)
{
return out;
}
Unfortunately, this is just a global function. Like any other global function, it cannot access the private members of Rational. To make it work with Rational objects, you need to make it friend of Rational:
class Rational
{
private: int m_t,m_b;
// ...
friend ostream& operator<<(ostream& out, const Rational& r);
};
ostream& operator<<(ostream& out, const Rational& r)
{
out << r.m_t << "/" <<r.m_b;
return out;
}
The friend ostream& operator<<(ostream& out, const Rational& r); inside Rational class indicates that ostream& operator<<(ostream& out, const Rational& r) function can directly use Rational's private members.
Now when you write:
Rational r(1, 2); // Say, it sets num and den
cout << r;
the following function call is made:
operator<<(cout, r);
Can you write operator<< as a member function of Rational? That's simply not possible because of the above conversion where cout has to be first parameter. If you make operator<< as a member of Rational:
class Rational
{
private: int m_t,m_b;
// ...
public:
ostream& operator<<(ostream& out) const
{
out << r.m_t << "/" <<r.m_b;
return out;
}
};
you need to call it this way:
Rational r(1, 2);
r.operator<<(cout);
which is ugly.