简体   繁体   中英

Accessing/filling a vector from a different class?

I am confused on how to fill a vector with values from a different class.

Can anyone give me a coded example how this is done. :)

Class A
{
   //vector is here
}
Class B
{
   //add values to the vector here
}
 main()
{
  //access the vector here, and print out the values
}

I appreciate the help <3

访问级别封装方面似乎是一个快速的课程。

My guess, based on the questions touch is that you're looking for the following code.

int main()
{
  ClassA[] as = {new ClassA(), new ClassA(), ... }
  ClassB[] bs = {new ClassB(), new ClassB(), ... }
}

But I'm shooting in the dark, a bit. :)

You should make your question more specific , edit it and post what you've tried to do . If you mean to do something respecting oop-rules, the play looks like this:

#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.
}

Note that this example above is a bit different from what you've asked . I posted it since I think you sould keep in mind that according to OOP rules

  • you don't want to access values in A directly,
  • B should have a member with type A if you plan to access a value in A,
  • you're supposed to access a value in A through B if you have filled it up from B.

The other way to go is not 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];
}

but this code is as horrible as it gets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM