如何访问封装向量中元素的公共成员?

问题描述 投票:0回答:1
class obj1{
public:
    void do(){}
    void some(){}
    void stuff(){}
};
class obj2{
public:
    void nowDo(){}
    void someOther(){}
    void things(){}
};

template <class T>
class structure{
public:
    /*
    access public members of Ts's elements while encapsulating the vector
    (preferably without copying all of obj's public members in the structure)
    */

private:
    vector <T *> Ts;
};

void foo(){
    structure <obj1 *> str1;
    structure <obj2 *> str2;
    /*
    Access public members of str1 and str2's elements 
    */
}

是否有一种方法可以访问'obj'元素的公共成员,同时将其向量封装在'结构'模板类中?

我更愿意这样做而不复制'结构'中的所有'obj'公共成员,因为我希望'structure'是一个同质化的模板类,这样我就不需要为每个对象创建一个唯一的数据结构我想要包含。

c++ object data-structures encapsulation member
1个回答
0
投票

那这个呢?

template <class T>
class structure{
public:

    size_t getCount()
    {
         return Ts.size();
    }

    T& getItem(size_t index)
    {
        return Ts[index];
    }

private:
    vector <T> Ts; // notice the change I made here.
};

然后在你的代码中,你可以这样说:

structure <obj1 *> str1;
size_t count = str1.getCount();
for (size_t i = 0; i < count; i++)
{
    str1->getItem(i)->Do();
    str1->getItem(i)->Some();
    str1->getItem(i)->Stuff();
}
© www.soinside.com 2019 - 2024. All rights reserved.