简体   繁体   中英

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.

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

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

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

您没有使用命名空间std(无论如何都习惯使用命名空间std),因此编译器不知道ostream到底是什么,除此之外,您实际上并没有定义operator <<,只是声明了它,所以即使如果它识别出它,它将不知道该怎么办,因为您没有告诉它。

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 .

考虑将您的对象作为参考传递,否则每次都会通过复制构造函数创建一个新的obj对象。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM