问题
I need to rewrite the << operator so that it can cout values for hour (int) and temperature (double).
I think I've included all necessary sections. Thanks in advance.
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(const Reading &r) const;
};
========
ostream& operator<<(ostream& ost, const Reading &r)
{
// unsure what to enter here
return ost;
}
========
vector<Reading> get_temps()
{
// stub version
cout << "Please enter name of input file name: ";
string name;
cin >> name;
ifstream ist(name.c_str());
if(!ist) error("can't open input file ", name);
vector<Reading> temps;
int hour;
double temperature;
while (ist >> hour >> temperature){
if (hour <0 || 23 <hour) error("hour out of range");
temps.push_back( Reading(hour,temperature));
}
}
回答1:
For example like this:
bool operator <(Reading const& left, Reading const& right)
{
return left.temperature < right.temperature;
}
And it should be a global function (or in the same namespace as Reading
), not a member or Reading
, it should be declared as a friend
if you going to have any protected or private members. This could be done like so:
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
friend bool operator <(Reading const& left, Reading const& right);
};
回答2:
You probably want something like
ost << r.hour << ' ' << r.temperature;
This is pretty simple stuff though, and if it doesn't make sense you should really talk to someone or get a book.
And if it still doesn't make sense or you can't be bothered, consider choosing another hobby/career.
回答3:
IIRC, you can do it one of two ways ...
// overload operator<
bool operator< ( const Reading & lhs, const Reading & rhs )
{
return lhs.temperature < rhs.temperature;
}
or, you can add the operator to your struct ...
struct Reading {
int hour;
double temperature;
Reading ( int h, double t ) : hour ( h ), temperature ( t ) { }
bool operator< ( const Reading & other ) { return temperature < other.temperature; }
}
回答4:
Use ost parameter like std::cout in operator<<.
回答5:
r.hour()
r.temperature()
You've declared hour
and temperature
as member fields of Reading
, not member methods. Thus they are simply r.hour
and r.temperature
(no ()
).
回答6:
As hour and temperature are variables rather than functions, just remove the trailing ()
from the operator<<
functions.
回答7:
You can overload an operator like this in c++.
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(struct Reading &other) {
//do your comparisons between this and other and return a value
}
}
来源:https://stackoverflow.com/questions/4362077/operator-rewrite-to-cout-int-and-double-values