I have to implement this simple Minimum class which keeps track of min and total, however I keep receiving this error: "error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream') and 'Minimum')". Is there a way to solve this issue? And it looks like it's coming from overloading << operator but I can't see where the problem is. Any help would be appreciated thank you!
#include <iostream>
#include <climits>
using namespace std;
class Minimum {
private :
int min;
int total;
public :
Minimum(int m = INT_MAX, int t = 0){
min = m;
total= t;
}
friend ostream& operator<<(ostream& os, Minimum& m) {
os << "Total = " << m.total << ", " << "min = " << m.min;
return os;
}
Minimum& operator+=(int num) {
total += num;
if (num < min) {
num = min;
}
return *this;
}
Minimum& operator++() {
total++;
return *this;
}
Minimum operator++(int) {
Minimum temp = *this;
total++;
return *this;
}
bool operator==(const Minimum& m) const {
return ((total == m.total) && (min == m.min));
}
bool operator!=(const Minimum& m) const {
return !(*this == m);
}
};
int main() {
Minimum m;
cout << m << endl;
m +=8;
cout << m << endl;
m +=6;
cout << m << endl;
m += 4;
cout << m << endl;
m += 5;
cout << m << endl;
cout << m++ << endl;
cout << m << endl;
cout << ++m << endl;
cout << m << endl;
(m += -10) += 3; // 2 calls chained together
cout << m << endl;
Minimum copy = m;
cout << copy << endl;
if (m != copy)
cout << "Different" << endl;
else
cout << "Equal" << endl;
}
You get this error here:
cout << m++ << endl;
That's because m++
returns a Minimum
r-value and the operator you defined expects a non-const l-value to Minimum
(ie Minimum&
). Change it to:
friend ostream& operator<<(ostream& os, Minimum const & m)
This works because const
l-values bind to r-values.
Also, most probably you have a bug in your post-increment operator as you should return the old value:
Minimum operator++(int) {
Minimum temp = *this;
total++;
//return *this;
return temp;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.