如何在局部 class 中定义友元函数运算符>>?
How to define a friend function operator>> inside a local class?
试图在本地 class 中重载输入运算符 >>
。我试图在 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
这是我的想法,根据我的评论,你会用 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;
}
};
试图在本地 class 中重载输入运算符 >>
。我试图在 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
这是我的想法,根据我的评论,你会用 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;
}
};