简体   繁体   中英

Friend function and protected data

I have class

    class ScoreBoard: public die
{ //..//
    protected:
    bool mSetValue[6];
    public:
//...//
        friend void ValueSet();
};

and I would like to use that friendship to get access to mSetValue . So what I do in ScoreBoard.cpp is: I predifine a funcion ( void ValueSet(); ) and then define it like this:

void ValueSet()
{ char lPick;
std::cin >> lPick;
if (lPick == 1) mSetValue[0] = true; }

But the debugger says:

'mSetValue' was not declared in this scope.

So, my question is - how to properly set a friendship so ValueSet can get access to mSetValue array?

Member variables exist inside instances (objects). They are also called "instance variables". If there is no instance of the class, then there is no instance variable.

mSetValue is a member variable of ScoreBoard . Therefore ScoreBoard::mSetValue instances exists only within an instance of ScoreBoard .

how to properly set a friendship so ValueSet can get access to mSetValue array?

In function void ValueSet() you don't have any instances of ScoreBoard . You cannot access ScoreBoard::mSetValue - regardless of its access specifier or friendship - because it doesn't exist. What you need is an instance of ScoreBoard .

I use this function inside the ScoreBoard class so I can't create any instance of ScoreBoard inside it

Nothing prevents you from creating an instance of ScoreBoard within a member function of ScoreBoard . Although, within a member function of ScoreBoard you already have access to an instance, which is pointed by this , so there might be no need to create a new instance. What you should do depends on your intention.

Given your comment, I suspect that a member function would be more appropriate for you, rather than a free function.

I use the generic term "Member variable" to refer non-static member variables for simplicity. Static member variables are different. They are also called class variables.

Friend functions are not member of class. So in your case if you want to use mSetValue in ValueSet then you have to provide some access to mSetValue via an instance or "object" of that class. This can be done by declaring your ValueSet() function as

friend void ValueSet(ScoreBoard &sb);

And your definition as

void ValueSet(ScoreBoard &sb)
{
    char lPick;
    std::cin >> lPick;
    if (lPick == 1)
        sb.mSetValue[0] = true; 
}

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