Reputation: 37
#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
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
Reputation: 420991
As I see it you need to
Add
using std::ostream;
using std::ofstream;
;
after the class declarationIn 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
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
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
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
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