类操作符的模糊重载>>

时间:2017-06-06 15:42:55

标签: c++

我正在尝试重载istream(>>)的类运算符,并且由于某种原因我收到错误Ambiguous overload for operator>>。 ostream的运算符完美运行但istream不运行。 有人知道为什么吗?

#include <iostream>
#include <fstream>
using namespace std;

class Person
{
    public:
      Person(string name="Empty", int num=0)
      :name(name), num(num){}

      friend istream& operator>> (istream& is, Person& o)
      {
        is >> o.name>> o.num;
         return is; 
      }

      friend ostream& operator<< (ostream& os, Person& o)
      {
        return os << o.name<< " " << o.num<< endl;
      }
    private:
      string name;
      int num;

};

int main()
{   
    ifstream fajl("input.txt");

    Person a();
    fajl >> a ;
    cout << a ;

}

input.txt中:

Name1 15
Name2 16

我收到错误:fajl >> a ;

1 个答案:

答案 0 :(得分:2)

这不是变量声明:

Person a();

函数声明。声明变量的正确代码是:

Person a;
相关问题