[英]Accessing/filling a vector from a different class?
我对如何用不同类的值填充向量感到困惑。
谁能给我一个编码示例,这是如何完成的。 :)
Class A
{
//vector is here
}
Class B
{
//add values to the vector here
}
main()
{
//access the vector here, and print out the values
}
感谢您的帮助<3
根据猜测的问题,我的猜测是您正在寻找以下代码。
int main()
{
ClassA[] as = {new ClassA(), new ClassA(), ... }
ClassB[] bs = {new ClassB(), new ClassB(), ... }
}
但是我在黑暗中射击。 :)
您应该使问题更具体 ,对其进行编辑并发表您的尝试 。 如果您打算做一些尊重规则的事情,那么这出戏看起来像这样:
#include<iostream>
#include<vector>
class A{
public:
void fill_up_the_vector() { v=std::vector<int>(3); v[0]=0; v[1]=1; v[2]=4; }
void add( a.add(i); ) { v.push_back(i); }
void display_last() const { std::cout<<v[v.size()-1]; }
private:
std::vector<int> v;
};
class B{
public:
B(){ a.fill_up_the_vector(); } // B just *instructs* A to fill up its vector.
void add_value(int i) { a.add(i); }
void display() const { a.display_last(); }
private:
A a;
};
int main()
{
B b;
b.add_value(9);
b.display(); // reads v through A.
}
请注意, 上面的示例与您要求的稍有不同 。 我发布了它,因为我认为您应该牢记根据OOP规则
另一种方法不是 OOP:
struct A{
std::vector<int> v;
};
struct B{
static void fill_A(A& a) const { a.v = std::vector<int>(3); a.v[0]=0; a.v[1]=1; a.v[2]=4; }
};
int main()
{
A a;
B::fill_A(a);
a.v.push_back(9);
std::cout << a.v[a.v.size()-1];
}
但是这段代码是可怕的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.