Friend function problem

From: Gactimus (gactimus_at_xrs.net)
Date: 11/24/04


Date: Wed, 24 Nov 2004 01:59:12 GMT

Hey again,

I am working my way through the book "C++ Primer Fourth Edition".

I am trying to run a program out of the book using Microsoft Visual C++
version 6 and I am given the error message:

: error C2248: 'hours' : cannot access private member declared in class 'Time'
: error C2248: 'minutes' : cannot access private member declared in class 'Time'

Here is the code. I have indicated where the compiler says the problem lies:

//mytime3.h
#ifndef MYTIME0_H_
#define MYTIME0_H_
#include <iostream>
using namespace std;

class Time
{
private:
        int hours;
        int minutes;
public:
        Time();
        Time(int h, int m = 0);
        void AddMin(int m);
        void AddHr(int h);
        void Reset(int h = 0, int m = 0);
        Time operator+(const Time & t) const;
        Time operator-(const Time & t) const;
        Time operator*(double n) const;
        friend Time operator*(double m, const Time & t)
                {return t * m;}
        friend ostream & operator<<(ostream & os, const Time & t);
};
#endif

// mytime3.cpp
#include "mytime3.h"

Time::Time()
{
        hours = minutes = 0;
}

Time::Time(int h, int m)
{
        hours = h;
        minutes = m;
}

void Time::AddMin(int m)
{
        minutes += m;
        hours += minutes / 60;
        minutes %= 60;
}

void Time::AddHr(int h)
{
        hours += h;
}

void Time::Reset(int h, int m)
{
        hours = h;
        minutes = m;
}

Time Time::operator+(const Time & t) const
{
        Time sum;
        sum.minutes = minutes + t.minutes;
        sum.hours = hours + t.hours + sum.minutes / 60;
        sum.minutes %= 60;
        return sum;
}

Time Time::operator-(const Time & t) const
{
        Time diff;
        int tot1, tot2;
        tot1 = t.minutes + 60 * t.hours;
        tot2 = minutes + 60 * hours;
        diff.minutes = (tot2 - tot1) % 60;
        diff.hours = (tot2 - tot1) / 60;
        return diff;
}

Time Time::operator*(double mult) const
{
        Time result;
        long totalminutes = hours * mult * 60 + minutes * mult;
        result.hours = totalminutes / 60;
        result.minutes = totalminutes % 60;
        return result;
}

//THE PROBLEM IS HERE
ostream & operator<<(ostream & os, const Time & t)
{
        os << t.hours << " hours, " << t.minutes << " minutes";
        return os;
}

//usertime3.cpp
#include <iostream>
#include "mytime3.h"
using namespace std;

int main()
{
        Time A;
        Time B(5, 40);
        Time C(2, 55);

        cout << "A, B, and C:\n";
        cout << A << "; " << B << "; " << endl;
        A = B + C;
        cout << "B + C: " << A << endl;
        A = B * 2.75;
        cout << "B * 2.75: " << A << endl;
        cout << "10 * B: " << 10 * B << endl;
        return 0;
}

Please help!!!



Relevant Pages