I'm new on C , and i'm trying to access a unordored map private from another cpp file but i've got some errors on compile.
I have declared the map like this:
class AccessList
{
private:
std::unordered_set<uint32_t> playerList;
};
on my other cpp file i could access the playerList if its was public like this:
auto playerIt = house->getGuestList().playerList.find(guid);
if (playerIt == house->getGuestList().playerList.end()) {
house->kickPlayer(nullptr, this);
}
However, if it can't be public because i've got some crashs on this way. It needed to be private. But how i could access this map? If i access like i did before, i get this error on compile:
error: ‘std::unordered_set<unsigned int> AccessList::playerList’ is private within this context
1192 | auto playerIt = house->getGuestList().playerList.find(guid);
I have tried setup a function on public to get the map from private, but without success..
Thank you very much.
CodePudding user response:
The whole idea of a private
class member is to control its accessibility from outside the class itself. If you need to access it, either make it public
or add a function that would return a pointer or reference to the private member.
But I'd rather elaborate why making it public
would cause a crash.
CodePudding user response:
The way i have figured out:
class AccessList
{
public:
std::unordered_set<uint32_t> getPlayerList() {
return playerList;
}
private:
std::unordered_set<uint32_t> playerList;
};
class House
{
public:
AccessList getGuestList() {
return guestList;
}
AccessList getSubOwnerList() {
return subOwnerList;
}
private:
AccessList guestList;
AccessList subOwnerList;
};
calling on other.cpp file:
auto playerIt = house->getGuestList().getPlayerList().find(guid);
if (playerIt == house->getGuestList().getPlayerList().end()) {
house->kickPlayer(nullptr, this);
}
However, it have a problem with access everytime guestList
by getGuestList()
?