简体   繁体   中英

cannot access private member declared in class

this is my first question in here :) i have i little problem.. these are my classes:

class Gracz{
    char znak_gracza;
public:
    Gracz();
    Gracz(char znak){
            this->znak_gracza = znak;
        };
    friend void multiplayer();
};
class Osoba: public Gracz{
public:
    Osoba();
    Osoba(char znak){
            this->znak_gracza = znak;
        };
    friend void multiplayer();
};

i also have a function multiplayer, where i try tu use constructor with argument:

void multiplayer(){
    Osoba gracz1('O');
    Osoba gracz2('X');
...
}

but it doesn't work.

errors are same for gracz1 and gracz2

error C2248: 'Gracz::znak_gracza' : cannot access private member declared in class 'Gracz'
see declaration of 'Gracz::znak_gracza'
see declaration of 'Gracz'

Derived classes cannot access private members of a parent class. You can declare them as protected (which is like private but lets derived classes access it), but in your case, since Gracz provides a way to initialize the variable, you should just let Osoba pass the argument to Gracz constructor.

Osoba(char znak)
    : Gracz(znak) // initializes parent class
{}

private member access is only available to members of the class, and friends. what you're looking for it to declare char znak_gracza as protected , so classes that inherit Gracz have access to that member as well.

your class Gracz should look more like this:

class Gracz{
protected:
    char znak_gracza;
public:
    Gracz();
    Gracz(char znak){
            this->znak_gracza = znak;
        };
    friend void multiplayer();
};

The constructor needs to pass the parameter to the base class constructor:

class Osoba: public Gracz{
public:
    //...
    Osoba(char znak) :
    Gracz(znak) {
    }

};

The multiplayer function is a friend of the Gracz class, but the Osoba class isn't.

Remember that child classes can't automatically access parent classes private variables. If you want Osoba to access the znak_gracza variable you have to make it protected .

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