views:

72

answers:

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

+2  A: 

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.

DeadMG
@DeadMG: But why 'ambiguous' symbol?
Chubsdad
A: 

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.

Kristo
+2  A: 

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);
Stephen Doyle
A: 

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.

Axel Gneiting
`using std::ostream;` is another possibility.
Jerry Coffin
+1  A: 

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();
}
aioobe
A: 

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);  
skimobear