Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error private within this context c++

Tags:

c++

I think I have been working on this code too long. Anyway here is whats happening.

header file (scope of the project forbids changing public)

#ifndef FRACTION_
#define FRACTION_

using namespace std;

#include <iostream>

class Fraction
{
  private:

    int num,denom;


  public:

    // Construct fraction from numerator and denominator
    //
    Fraction( int = 0, int = 1 );

    // Construct fraction by copying existing fraction
    //
    Fraction( const Fraction& );

    // Assign into fraction by copying existing fraction
    //
    Fraction& operator=( const Fraction& );

    // Return true if fraction is valid (non-zero denominator)
    //
    bool IsValid() const;

    // Return value of numerator
    //
    int Numerator() const;

    // Return value of denominator
    //
    int Denominator() const;

    // Input/Output operations
    //
    friend istream& operator>>( istream&, Fraction& );
    friend ostream& operator<<( ostream&, const Fraction& );
};

// Comparative operations
//
bool operator==( const Fraction&, const Fraction& );
bool operator!=( const Fraction&, const Fraction& );
bool operator< ( const Fraction&, const Fraction& );
bool operator<=( const Fraction&, const Fraction& );
bool operator> ( const Fraction&, const Fraction& );
bool operator>=( const Fraction&, const Fraction& );

// Arithmetic operations
//
Fraction operator+( const Fraction&, const Fraction& );
Fraction operator-( const Fraction&, const Fraction& );
Fraction operator*( const Fraction&, const Fraction& );
Fraction operator/( const Fraction&, const Fraction& );

#endif

I am trying to overload the + operator, here is my code for that:

Fraction operator+(const Fraction &f1, const Fraction &f2)
{
    return(((f1.num*f2.denom)+(f1.denom*f2.num)),(f1.denom*f2.denom));
}

I get an error about referencing num and denom as private variable, I am just having a hard time figuring out how to correct that problem.

like image 469
sharkman Avatar asked Oct 19 '12 01:10

sharkman


1 Answers

Use Numerator() instead of num and Denominator() instead of denom. Your operator is not a member, nor a friend, so it can't access private members.

The other option would be to

  • make it a member (but making an operator that can be a free function a member has several disadvantages, including that you can't say 5 + frac, only frac + 5)
  • make it a friend, (but making it a friend when it doesn't have to be increases the number of things that have access to the class not through its interface, leading to increased code maintenance)
like image 60
chris Avatar answered Nov 06 '22 19:11

chris