1

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.

김택정
  • 19
  • 2
  • In the second case HHMM became a member method. Inside the class it would need to be declared static, and called with Clock::HHMM. But I think you will get better advise from daily C++ users. – Joop Eggen Sep 12 '21 at 18:03

1 Answers1

0

In the first code, the function "Clock HHMM()" is not a member of the class and an independent function declared outside the class. So, the main can easily call it. For the definition of the function you mentioned in the class, you need to write "Clock Clock::HHMM()". In the second case, the function is a private member of the class, therefore, you cannot call it. The compiler cannot call the private function outside the class and hence gives an "undefined" error. Note: The default access specifier of a class is private.