简体   繁体   中英

Cannot access private member declared in class

I am working with operator overloads for the first time and am setting up the overload for the extraction operator (<<). I'm stuck in one of two errors that are preventing me from continuing. The code is as follows:

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 issue I encounter is that when the overload is formatted this way (which is as far as I can tell, the correct way) it does not allow me to access the miles, yards, feet, or inches member data, despite the function being set as a friend in the header file.

If I change the overload to 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 does not work in my main function as it returns the error:

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

for every instance of cout in the function. Plus, the previous examples I have show that this would be incorrect. What am I doing wrong in the first code example that is preventing me from accessing the private member data? I've looked at several other instances of this being asked on various sites, but nothing quite matches what I am getting. I have tried compiling with Visual Studio Express 2012 and g++, both return the error.

The declaration inside the class definition should be:

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

The error in your first attempt is because when you write a function ostream &operator<< (ostream &output, const Distance &d1) , this is not the same function you friended because it has different arguments.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM