1.11M Members

Access vector object class in another class..

 
0
 

Suppose I have a code:
Class A have items which is pushed into a vector...I want to access Class A element from class B through A's vector..

class A
{
    friend class B;
    vector<A> data; //store info in vector
};

Class B
{
    void showDataInClassA();
    A a;

}
void B::showDataInClassA()
{
    vector<A>::iterator p= a.data.begin();
    while(p != a.data.end())
    {
        //cout<<p->getUserName();
        ++p;
      }

}

However, it doesnt show up. May I get any advice?
Thanks.

 
0
 

the vector is not populated with anything.

#include <vector>
#include <string>
#include <iostream>

using namespace std;

class B;

class A
{
public:
    friend B;
    A(string n) {username = n;}
    A() {}
    static vector<A*> data; //store info in vector
    string getUserName() {return username;}
protected:
    string username;

};

class B
{
public:
    B() {}
    void showDataInClassA();
    A a;
};

void B::showDataInClassA()
{
    vector<A*>::iterator p= a.data.begin();
    while(p != a.data.end())
    {
        cout<< (*p)->getUserName();
        ++p;
      }
}
vector<A*> A::data; //store info in vector

int main()
{
    A::data.push_back(new A("One"));
    A::data.push_back(new A("Two"));
    A::data.push_back(new A("Three"));
    B b;
    b.showDataInClassA();
    return 0;
}
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article