如何定义朋友函数运算符>>在本地课堂内?

时间:2017-11-19 15:42:10

标签: c++ operator-overloading friend-function local-class

尝试在本地类中重载输入操作符>>。我尝试在friend istream &operator >>内定义class Data

int readFile(char* file_name,float temperature_data[][31])
{
    class Data
    {
        public:
            int day,month,year;
            float temp;
            friend istream & operator >> (istream &in,  Data &c)
            {
                char ch;
                in >> c.day;
                in >>  ch;
                in >> c.month;
                in >>  ch;
                in >> c.year;
                in >>  ch;
                in >> c.temp;
                return in;
            }
    };
    freopen(file_name,"r",stdin);
    int i;
    Data d;
    for(i=0;;i++)
    {
        int total=0;
        char ch;
        cin>>d;
        temperature_data[d.month-1][d.day-1] = d.temp;
        ch = getchar();
        if(ch==EOF)
            break;
    }
    fclose(stdin);
    return d.year;
}

显示错误:

error: can't define friend function 'operator>>' in a local class definition

1 个答案:

答案 0 :(得分:0)

以下是我的想法,从我的评论中,您可以使用d.read(cin)打电话:

class Data {
public:
  int day,month,year;
  float temp;
  void read(istream& in) {
    char ch;
    in >> day;
    in >> ch;
    in >> month;
    in >> ch;
    in >> year;
    in >> ch;
    in >> temp;
  }
};