【问题标题】:How to define a friend function operator>> inside a local class?如何在本地类中定义友元函数运算符>>?
【发布时间】:2017-11-19 15:42:10
【问题描述】:

试图在本地类中重载输入运算符>>。我试图在class Data 中定义friend istream &operator >>

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

【问题讨论】:

  • 当且仅当类是非本地类 (9.8)、函数名是非限定的且函数具有命名空间范围时,才能在类的友元声明中定义函数。
  • 有什么解决方法吗?我正在尝试重载 >> 运算符以进行输入。我必须在函数 readFile 中执行此操作。谢谢
  • 解决方法是不使用operator>>,而是创建一个read(istream& in)方法,并通过d.read(cin)调用它。
  • 我正在尝试听从你的建议,Eljay。如果你能给我举例说明如何使用read(istream& in),那将非常有帮助。谢谢

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


【解决方案1】:

这是我的想法,来自我的评论,您可以使用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;
  }
};

【讨论】:

  • 谢谢..它成功了。是否可以通过重载operator >> 来实现?
  • 不,根据 JLev 的评论,您不能这样做,因为您有本地课程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2011-05-16
  • 2016-01-23
  • 2015-07-23
相关资源
最近更新 更多