Operator << overload in c++
#include <iostream>
#include &开发者_开发问答lt;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.
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);
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.
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();
}
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.
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
.
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);
精彩评论