I have 2 classes (firstClass
and secondClass
) of which firstClass
is a friend of secondClass
, and has a private nested std::unordered_map
, which I want to access it in a function of secondClass
.
So basically the code is like this:
class secondClass;
typedef unordered_map STable<unsigned, unordered_map<unsigned, double> > NESTED_MAP;
class firstClass {
friend class secondClass;
void myfunc1(secondClass* sc) {
sc->myfunc2(&STable);
}
private:
NESTED_MAP STable;
};
class secondClass {
public:
void myfunc2(NESTED_MAP* st) {
//Here I want to insert some elements in STable.
//Something like:
st[1][2] = 0.5;
}
};
int main() {
firstClass fco;
secondClass sco;
fco.myfunc1(&sco);
return 0;
}
The point is that if instead of the nested map, I use a simple std::unordered_map
, I can easily modify it (add new elements, or change the values of some keys). But, in the nested map I can not do anything.
I know that it should be trivial, but I don't know how to solve it. Any idea?
You are not passing by reference, you're passing a pointer. This is a version using reference:
void myfunc2(NESTED_MAP &st)
{
st[1][2] = 0.5; // valid, st dereferenced implicitly
}
And call it without address-of operator:
sc->myfunc2(STable);
If you really want to pass a pointer, it needs explicit dereferencing:
void myfunc2(NESTED_MAP *st)
{
(*st)[1][2] = 0.5;
// or, if you like:
st->operator[](1)[2] = 0.5;
}
In the code you posted, you firstClass
has only private members (forgot public:
?).