while playing with the code, I have found an issue. When declaring friend function and putting body outside the class gives no error.
#include <iostream>
using namespace std;
class Clock
{
friend ostream& operator<<(ostream& os, const Clock& c)
{
return os << c.hour << " hr. " << c.minute << " min. ";
};
friend Clock HHMM(int hhmm);
public:
Clock() : hour(0), minute(0) { }
static Clock minutes(int m)
{
return Clock(m / 60, m % 60);
}
private:
int hour, minute;
Clock(int h, int m) : hour(h), minute(m) { }
};
Clock HHMM(int hhmm) {
return Clock(hhmm / 100, hhmm % 100);
}
int main()
{
Clock c1; // 0:00
Clock c2 = HHMM(123); // 1:23
Clock c3 = Clock::minutes(123); // 2:03
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
return 0;
}
But when putting body inside the class gives error.
#include <iostream>
using namespace std;
class Clock
{
friend ostream& operator<<(ostream& os, const Clock& c)
{
return os << c.hour << " hr. " << c.minute << " min. ";
};
friend Clock HHMM(int hhmm) {
return Clock(hhmm / 100, hhmm % 100);
};
public:
Clock() : hour(0), minute(0) { }
static Clock minutes(int m)
{
return Clock(m / 60, m % 60);
}
private:
int hour, minute;
Clock(int h, int m) : hour(h), minute(m) { }
};
int main()
{
Clock c1; // 0:00
Clock c2 = HHMM(123); // 1:23
Clock c3 = Clock::minutes(123); // 2:03
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
return 0;
}
error: identifier "HHMM" is undefined. I think they are the same code but I have no clue why one works and others does not. Please help.