C ++中的朋友方法不工作 [英] Friend methods in C++ is not working

查看:140
本文介绍了C ++中的朋友方法不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码:

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;
    }
};

,此行加下划线:

cout << super::imie; 

它说它不可访问。但在我看来是 - 我赞这种方法。
我尝试了类Dziecko的前瞻性声明 - 也没有工作。我做错了什么?

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?

推荐答案

看来你不能调用该方法,因为它使用类<$ c的私有成员$ c> Osoba 。

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

尝试使用 imie 私人。

以下是一个简短的 Explenation

有两个选项:

1) friend 整个类,不是使用继承的好习惯。

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

2)使用受保护的成员。这是访问私有成员继承的最好方法。

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

这篇关于C ++中的朋友方法不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆