Cannot access a private member declared in a class

I am working with operator overloads for the first time and am setting an overload for the extract operator (<<). I am stuck with one of two errors preventing me from continuing. The code looks like this:

ostream &operator << (ostream &output, const Distance &d1)
{
    if (d1.miles > 0)
    {
        output << d1.miles << "m ";
    }    
    if (d1.yards > 0)
    {
        output << d1.yards << "y ";
    }
    if (d1.feet > 0)
    {
        output << d1.feet << "\' ";
    }

    output << d1.inches << "\"";

    return (output);
}

      

The overload is declared as a friend in the header file as follows:

friend ostream &operator<< (ostream output, const Distance &d1);

      

The first problem I run into is that when the overload is formatted this way (the correct way to go as far as I can tell), it prevents me from accessing data on members of miles, yards, feet, or inches, despite the fact that the function was defined as a friend in the header file.

If I change the overload read:

ostream &operator << (ostream output, const Distance &d1)
{
    if (d1.miles > 0)
    {
        output << d1.miles << "m ";
    }    
    if (d1.yards > 0)
    {
        output << d1.yards << "y ";
    }
    if (d1.feet > 0)
    {
        output << d1.feet << "\' ";
    }

    output << d1.inches << "\"";

    return (output);
}

      

Then the overload works correctly, but it doesn't work in my main function as it returns an error:

error C2248: 'std::basic_ostream<_Elem,_Traits>::basic_ostream' : cannot access private member declared in class 'std::basic_ostream<_Elem,_Traits>'

      

for each instance of cout in the function. In addition to the previous examples, I show that this would be wrong. What am I doing wrong in the first code example that is preventing me from accessing private member data? I have looked at a few other cases where you have been asked on different sites, but nothing matches what I get. I tried to compile with Visual Studio Express 2012 and g ++, both return an error.

+3


source to share


1 answer


The declaration inside the class definition should be:

friend ostream &operator<< (ostream &output, const Distance &d1);
//                                  ^--- important

      



The mistake in your first try is that when you write the function ostream &operator<< (ostream &output, const Distance &d1)

, it is not the function you are friends with, because it has different arguments.

The second attempt should have various errors as it is not allowed to pass the ostream value by value.

+4


source







All Articles