ベクトルを別のクラスの値で埋める方法について混乱しています。
これがどのように行われるか、コード化された例を誰か教えてください。:)
Class A
{
//vector is here
}
Class B
{
//add values to the vector here
}
main()
{
//access the vector here, and print out the values
}
助けてくれてありがとう<3
質問をより具体的にし、編集して、試したことを投稿する必要があります。oop-rules を尊重することを意図している場合、プレイは次のようになります。
#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];
}
しかし、このコードは恐ろしいものです。
私の推測では、質問のタッチに基づいて、次のコードを探していると思います。
int main()
{
ClassA[] as = {new ClassA(), new ClassA(), ... }
ClassB[] bs = {new ClassB(), new ClassB(), ... }
}
しかし、私は少し暗い中で撮影しています。:)