Shreekanth
Shreekanth

Reputation: 37

Operator << overload in c++

#include <iostream>
#include <fstream>

class obj
{
public:
 int i;
 friend ostream& operator<<(ostream& stream, obj o);
}

void main()
{
 obj o;
 ofstream fout("data.txt");
 fout<<o;
 fout.close();
}

This is the my code, am getting error. error : ostream : ambiguous symbol.

any one can help me.

Upvotes: 1

Views: 324

Answers (6)

skimobear
skimobear

Reputation: 1198

Consider passing your object in as a reference otherwise a new obj object will be created each time via the copy constructor.

friend ostream& operator<<(ostream& stream, obj& o);  

Upvotes: 0

aioobe
aioobe

Reputation: 420991

As I see it you need to

  • Add

    using std::ostream;
    using std::ofstream;

  • Add a ; after the class declaration
  • Povide an implementation for the << operator.

In the end you should end up with something like:

#include <iostream>
#include <fstream>

using std::ostream;
using std::ofstream;

class obj
{
public:
 int i;
 friend ostream& operator<<(ostream& stream, const obj& o);
};

ostream& operator<<(ostream& stream, const obj& o)
{
  std::cout << o.i;
  return stream;
}

int main()
{
  obj o;
  ofstream fout("data.txt");
  fout << o;
  fout.close();
}

Upvotes: 1

Axel Gneiting
Axel Gneiting

Reputation: 5403

ostream is a member of the std:: namespace, so either put a using namespace std; before your class declaration or explicitly refer to it with std::ostream.

Upvotes: 0

Stephen Doyle
Stephen Doyle

Reputation: 3744

You need to specify the namespace. Prefix ostream with std - i.e. std::ostream

Also, you should pass the obj type by const reference to the operator:

friend ostream& operator<<(ostream& stream, const obj& o);

Upvotes: 3

Michael Kristofik
Michael Kristofik

Reputation: 35188

ofstream is in namespace std, so you need to declare fout like this:

std::ofstream fout("data.txt");

I'll assume you simply omitted the definition of your operator<< function for simplicity. Obviously, you'll need to write the body of that function for your next line to compile.

Upvotes: 0

Puppy
Puppy

Reputation: 146930

You didn't use namespace std (using namespace std is habit anyway) so the compiler doesn't know what on earth an ostream is.In addition to that, you didn't actually define operator<<, only declared it, so even if it recognizes it, it won't know what to do since you didn't tell it.

Upvotes: 2

Related Questions