Is it possible to implement a function to access a private data vector foo
in a class via class[i][j]
? This should call the inn开发者_开发百科er function of the vector foo[i][j]
.
A simple solution is to implement operator[]
so it "peels off" only the first dimension:
#include <cstdlib>
class MyClass
{
std::vector<std::vector<int> > foo;
public:
// grant write access
std::vector<int>& operator[](size_t index)
{
return foo[index];
}
// grant read access
const std::vector<int>& operator[](size_t index) const
{
return foo[index];
}
};
You need the two overloads because of const correctness. (If you only want to grant read access, not write access, you don't need the non-const version, of course.)
You can overload operator[]
to do this. You might want to look at this faq for advice for using operator()
instead.
精彩评论