overloading ostream operator

Dec 1, 2013 at 1:11am
I am writing a class in which I need to overload the << operator but it keeps giving me a too many parameters for this operator function error. That does not make sense because I am overloading the function so I can make it do whatever I want I would think. I am using a book while learning and they do it the same way so maybe I am just missing something >.< Btw this is just the prototype in the class header.

 
  ostream operator<< (ostream &strm, const Rational &obj);
Last edited on Dec 1, 2013 at 1:12am
Dec 1, 2013 at 1:18am
i believe that the & is the main problem:
ostream&operator<< (ostream &stream, const Rational obj);

and you must to put: stream not strm....

remember to write a return stream when you end the function...

Dec 1, 2013 at 1:18am
Rational.h

1
2
3
4
5
class Rational{
public:
friend ostream &operator<<(ostream&, const Rational&);
...
};


Rational.cpp

1
2
3
4
#include "Rational.h"
ostream &operator<<(ostream& strm, const Rational& obj){
...
}
Last edited on Dec 1, 2013 at 1:22am
Dec 1, 2013 at 1:39am
#include <iostream>
using namespace std;
class morgiana{
int x,y,z;
public:
friend ostream&operator<<(ostream&stream,morgiana obj);
morgiana(int a,int b, int c){x=a; y=b; z=c;}

};

ostream&operator<<(ostream&stream,morgiana obj)
{stream<<obj.x<<" ";
stream<<obj.y<<" ";
stream<<obj.z<<endl;
return stream;}

int main()
{
morgiana a(1,2,3),b(4,5,6),c(7,8,9);
cout<<a<<b<<c;

return 0;
}
Dec 1, 2013 at 1:40am
ahhh I see making them friend member functions works, but restricts access to the private member variables.
Dec 1, 2013 at 1:44am
Doesn't restrict access making something a friend would be like...

Giving someone the spare keys to your house. They may not be in the class but now they have access to everything.
Dec 1, 2013 at 1:52am
Hm then why is it restricting access. According to what I just read on friend member functions it should allow you to access private variables. Class header: friend istream &operator>> (istream &, Rational &);
implementation file:
1
2
3
4
5
6
7
8
9
10
istream &operator>>(istream& stream, Rational& obj)
{
	cout << "Numerator for first number: ";
	stream >> obj.p;
	cout << endl;
	cout << "Denominator for first number: ";
	stream >> obj.q;
	cout << endl;
	return stream;
}

Yet p and q are both inaccesible.
Dec 1, 2013 at 2:00am
Derrrrrrrrrrp I found my retard cap, was right next to the I never put using namespace std in the header file.
Topic archived. No new replies allowed.