<< Operator Rewrite to cout int and double values
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;
}
========开发者_StackOverflow中文版
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));
}
}
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);
};
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.
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; }
}
Use ost parameter like std::cout in operator<<.
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 ()
).
As hour and temperature are variables rather than functions, just remove the trailing ()
from the operator<<
functions.
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
}
}
精彩评论