如何正确访问受保护的变量?

How to access a Protected Variable Correctly?

我正在尝试使用 components.cpp[=27 从 items.h class 访问受保护变量之一=] class 但我得到的错误让我感到困惑::D

Item::Quantity': cannot access forbidden protected member declared in class 'Item'

item.h

 protected:
        int32 Quantity;

component.h

#include "Items/Item.h"
Item* AddItem(class Item* Item, const int32 Quantity);

component.cpp

ItemAddResult Component::TryAddItem_Internal(class Item* Item)
{
    Items.Add(Item);
    return ItemAddResult::AddedAll(Item->Quantity);
}

您可以通过添加 好友声明 使 class Component 成为 class Itemfriend 来解决此问题里面classItem如下图:

item.h

class Item{
    friend class Component;
    protected: 
        int32 Quantity;
    //other members here
}