从其他类访问向量的向量值

Accessing, and push_back values of a vector from a different class?

本文关键字:向量 访问 其他      更新时间:2023-10-16

我总体上对如何访问向量并从其他类中添加值。

我想从其他类中添加值(向量是私有的)。我还想访问Main()中的向量并能够将其打印出来。

谁能给我一个例子说明这是如何完成的?

Class A
{
//vector is here - it's a private vector
}
Class B
{
//add values to the vector here
}
main()
{
//access the vector here, and print out the values
}

如果向量是A的私人成员,则提供访问的通常方法是通过A的公共成员函数将访问向量访问。通常,您应该仅揭示必要的访问权限。阅读有关封装的信息。如果您打算为其提供完整的公共接口,那么将矢量私有的意义没有太大的意义。如果您只希望B类可以不受限制地访问它(以及A的其他成员),则可以使B成为A的朋友类。