0

I was just learning about friend classes and overloading operators in C++ where I came upon an issue where I cannot access the private variables in the friend class. I'm almost sure this has to do with the fact we were required to have each file separate (Header, .cpp and main). Need some fresh eyes.

// Contents of Percent.h

#ifndef PERCENT_H
#define PERCENT_H

#pragma once

class Percent
{
    // friend const Percent operator >>(Percent& first, Percent& second);
public:
    friend bool operator ==(const Percent& first,
        const Percent& second);

    friend bool operator <(const Percent& first,
        const Percent& second);
    Percent();

    friend istream& operator >>(istream& inputStream,
        Percent& aPercent);

    friend ostream& operator <<(ostream& outputStream,
        const Percent& aPercent);
    //There will be other members and friends.
private:
    int value;
};

// Contents of Percent.cpp

#include <iostream>
#include "Percent.h"

using namespace std;

istream& operator >>(istream& inputStream,
    Percent& aPercent)
{
    char percentSign;
                        ERROR HERE - Cannot access value
    inputStream >> aPercent.value;
    inputStream >> percentSign;
    return inputStream;
}

ostream& operator <<(ostream& outputStream,
    const Percent& aPercent)
{
    outputStream << aPercent.value << '%';
    return outputStream;
}
#endif // !PERCENT_H

// Main.cpp not written yet

drayk73019
  • 17
  • 5
  • 1
    In the header file, add an `#include ` at the top. And, use the full names `std::istream` and `std::ostream` instead of `istream` and `ostream`. Without that, the `friend` declarations are of a different function that the ones being defined in `Percent.cpp`. – Peter Oct 14 '19 at 18:36
  • FYI: `#ifndef PERCENT_H #define PERCENT_H #endif` and `#pragma once` do the same thing; you don't need both. – 0x5453 Oct 14 '19 at 18:54

0 Answers0