访问其他类中多个对象的私有成员向量 [英] Access private member vector of multiple objects in other class
问题描述
我有两个结构相似的类(A和B),都包含一个结构向量.
I have two classes (A & B) with a similar structure, which both contain a vector of structs.
class A/B{
private: std::vector<DataStruct> vec_A/vec_B;
...
public:
...
}
要创建/更新B对象,我必须组合来自A类多个对象的矢量的数据(将矢量中的相似条目组合到对象B的矢量中的一个条目,然后在B中进行数据转换)
To create/update an object of B, I have to combine the data from the vectors of multiple objects of class A (combining similar entries in the vector into one entry in the vector of object B and do data transformations in B).
我该怎么做?
我的想法是:
- 让B类成为A的朋友.但是我听说,在C ++中成为类的朋友只是万不得已,应该避免.
- 在类A中编写一个
getVector()
函数,该函数返回对Vectorvec_A
的引用,以便类B可以对数据进行操作.对我来说,这似乎只是绕过了数据封装.将载体设置为公开有什么好处? - 在类A中编写一个
getVector()
函数,该函数返回vec_A
的副本.但是由于vec_A
并不是那么小,所以效率似乎很低(好,只有几kB.应该可以,但总的来说...) - 为A类编写一个函数,该函数进行计算并创建B类的对象.然后将B的多个对象连接到B的一个最终对象中.但是,这似乎给我带来了很多开销.
- Making class B a friend of A. But I've heard, that making classes friends in C++ is only the last resort and should be avoided.
- Writing a
getVector()
function in class A, which returns a reference to the Vectorvec_A
, so that class B can operate on the data. For me this seems to simply bypass the data encapsulation. What would be the advantage to setting the vector to public? - Writing a
getVector()
function in class A, which returns a copy ofvec_A
. But asvec_A
is not that small, this seems to be inefficient (ok, only a few kB. Should work but in general...) - Write a function for class A, which does the calculation and creates an object of class B. Then concatenate multiple objects of B into one final object of B. However, this seems to be a lot of overhead to me.
推荐答案
在类A中编写一个
getVector()
函数,该函数返回一个引用到Vector vec_A
上,以便B类可以对数据进行操作.为我这似乎只是绕过了数据封装.那会是什么将向量设置为公开有什么好处?
Writing a
getVector()
function in class A, which returns a reference to theVector vec_A
, so that class B can operate on the data. For me this seems to simply bypass the data encapsulation. What would be the advantage to setting the vector to public?
如果B只是需要观察 vec_A
的内容,请考虑返回一个 const
参考( const&
):
If B just needs to observe the content of vec_A
, consider returning a const
reference (const &
):
class A {
...
public:
// Give read-only access to vec_A
const std::vector<DataStruct> & getVector() const {
return vec_A;
}
};
我更喜欢这种解决方案,而不是仅仅公开矢量数据成员:使用访问器(getter/setter),您可以更好地进行控制.例如,您可以实现只读访问(如上图所示).或者,如果您想提供设置器,还可以对输入参数进行一些检查,等等.
I prefer this solution to just making the vector data member public: with accessors (getter/setter) you have better control. For example you can implement a read-only access (like shown above). Or, if you want to provide a setter, you can also implement some checking on the input argument, etc.
这篇关于访问其他类中多个对象的私有成员向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!