如何访问封装向量中元素的 public 成员?
How to access public members of elements in an encapsulated vector?
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' 元素的 public 成员,同时将其向量封装在 'structure' 模板 class 中?
我更愿意这样做而不复制 'structure' 中的所有 'obj' public 成员,因为我希望 'structure' 成为同质化模板 class, 这样我就不需要为我想包含的每个对象创建一个唯一的数据结构。
这个呢?
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();
}
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' 元素的 public 成员,同时将其向量封装在 'structure' 模板 class 中?
我更愿意这样做而不复制 'structure' 中的所有 'obj' public 成员,因为我希望 'structure' 成为同质化模板 class, 这样我就不需要为我想包含的每个对象创建一个唯一的数据结构。
这个呢?
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();
}