开发者

Access Vector in class with "class[i]" like class would be the vector

开发者 https://www.devze.com 2023-01-27 13:28 出处:网络
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 t

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消