Skip to main content
gamedev.net
🔒 Locked

overloaded insertion operator

Started by chyke Oct 12, 2005 at 11:06 AM 1 replies 650+ views
Original Post
chyke
chyke
Getting this error using VC++ with SP6. What could I be doing wrong? error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class ClockDigit' (or there is no acceptable conversion). Here is the code: #include using namespace std; class ClockDigit { public: ClockDigit(int b, ClockDigit *n = 0):base(b), count(0), nextdigit(n){} void increment(); void Set(int i) { if ((i >= 0) && (i < base)) count = i; } int theCount() const {return count;} private: int count; // increment this periodically const int base; // when (count >= base), reset count to 0 ClockDigit *const nextdigit; }; void ClockDigit::increment() { ++count; if (count >= base) { count = 0; if (nextdigit != 0) nextdigit -> increment(); // carry over } } class Clock { public: Clock():second(60, &minute), minute(60, &hour), hour(24){} void Set(int h, int m, int s) {hour.Set(h); minute.Set(m); second.Set(s);} void increment() {second.increment();} friend ostream& operator<<(ostream &os, const Clock &mc); private: ClockDigit second; ClockDigit minute; ClockDigit hour; }; ostream& operator<<(ostream &os, const Clock &mc) { Clock CL; os << CL.hour << ":" << CL.minute << ":" << CL.second << "\n"; return os; } int main() { Clock CL; CL.Set(23, 59, 50); for (int ii=0; ii < 100; ii++) { cout << CL << "\n"; CL.increment(); } return 0; }
TomH
TomH
Chyke,

:) It's exactly what the error says you haven't provided an operator '<<' for Clock*DIGIT*. You've provided an operator '<<' for Clock that uses the ClockDigit's '<<'.

Two easy fixes: 1) provide a similar '<<' for ClockDigit or 2) write Clock's '<<' without itself using ClockDigit's '<<'.

// Example 2)//  use operator<<(ostream&, const int) rather //  than operator<<(ostream&, const ClockDigit& )ostream& operator<<(ostream &os, const Clock &mc){Clock CL;os << CL.hour.theCount() << ":" << CL.minute.theCount() << ":" << CL.second.theCount() << "\n";return os;}


Cheers,

Tom
chyke
chyke
Thanks a lot Tom. It worked.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.