Friend methods in C++ is not working

不打扰是莪最后的温柔 提交于 2019-12-02 19:51:04

问题


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.



来源:https://stackoverflow.com/questions/20954195/friend-methods-in-c-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!