[英]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.