Friend methods in C++ is not working

2019-03-03 23:49发布

问题:

I wrote the following code:

class Osoba{
private:
    string imie, nazwisko, kolorOczu;
    friend void Dziecko::coutall();
public:
    Osoba(string imie, string nazwisko, string kolorOczu):imie(imie), nazwisko(nazwisko), kolorOczu(kolorOczu){};
    void coutall(){
        cout << "Imie: " << imie << endl; //
        cout << "Nazwisko: " << nazwisko << endl;
        cout << "Kolor oczu: " << kolorOczu << endl;
    }

};

class Dziecko: public Osoba{
private:
    string nazwaPrzedszkola, choroba;
    typedef Osoba super;
public:
    Dziecko(string imie, string nazwisko, string kolorOczu, string nazwaPrzedszkola, string choroba):super(imie, nazwisko, kolorOczu), nazwaPrzedszkola(nazwaPrzedszkola), choroba(choroba){};
    void coutall(){
        cout << super::imie; // this one gets underlined.
        cout << "Nazwa przedszkola: " << nazwaPrzedszkola << endl;
        cout << "Choroba: " << choroba << endl;
    }
};

and this line is underlined:

cout << super::imie; 

It says it's inaccessible. But in my opinion it is - I "friended" this method. I tried a forward declaration of class Dziecko - didn't work, either. What am I doing wrong?

回答1:

You cannot do it, because Dziecko::coutall is not defined when Osoba is compiled and there are no means in c++ to make forward member method declaration. Instead you can make friend all Dziecko class (as Nbr44 suggested)



回答2:

It seems you can't call that method because it uses private members of class Osoba.

Try using the imie as a protected variable instead of private.

Here is a short explenation.

The 2 options available are:

1) friend the entire class, not a good practice when using inheritance.

2) Use protected members. this is the best way to access private members on inheritance.