overloading ostream operator

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
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...

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
#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;
}
ahhh I see making them friend member functions works, but restricts access to the private member variables.
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.
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.
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.