简体   繁体   English

如何在 C++ 中访问另一个类中的向量对象

[英]how to access vector object in another class in c++

I am newbie to c++.I have created two classes.one class(say A) will push the struct data into vector while other class(say B) will pop out the data from the vector.我是 c++ 的新手。我创建了两个类。一个类(比如 A)会将结构数据推送到向量中,而其他类(比如 B)将从向量中弹出数据。

How do I pass the reference of vector from class A to B so that class B can point to same vector object to pop out data,to do some manipulation.如何将向量的引用从 A 类传递到 B,以便 B 类可以指向相同的向量对象以弹出数据,进行一些操作。

can anyone help me to resolve this谁能帮我解决这个问题

So far My effort is, Ah file:到目前为止,我的努力是,啊文件:

struct strctOfA {
       int x;
       int y;
       int z;
    };  


class A {
public:

A();        
private:
     std::vector<strctOfA> t2;
};

A.cpp file: A.cpp 文件:

         A::A() {

        strctOfA player;
        player.x=1;
        player.y=2;
        player.z=3;



        t2.push_back(player)
        B b;
        b.functionOfB(&t2); 
        }

Bh file Bh文件

         class B {

        public:
             B();
             functionOfB(&t2);
        };

B.cpp: B.cpp:

 B::functionOfB(A &t) {
    t2.pop_front(); 
    }

Use a friend class, this is a class that has been declared as friend (with the keyword friend) in another class.使用友元类,该类已在另一个类中声明为友元(使用关键字友元)。 It can access private and protected members of other class.它可以访问其他类的私有成员和受保护成员。 It is useful to allow a particular class to access private members of the other class.允许特定类访问另一个类的私有成员很有用。 Example:例子:

ah

typedef struct strctOfA {
   int x;
   int y;
   int z;
}positions;
class A {
public:
    A();
    friend class B;
private:
    strctOfA player;
    std::vector<positions> t2;
};

a.cpp a.cpp

    A::A() {
    player.x=1;
    player.y=2;
    player.z=3;
    t2.push_back(player);
}

bh

class B {
public:
    B();
    void functionOfB(A &x);
};

b.cpp b.cpp

B::B() {
}
void B::functionOfB(A &x) {
    x.t2.pop_back();
}

main.cpp主程序

int main() {
    A instanceOfA;
    B *instanceOfB = new B();
    instanceOfB->functionOfB(instanceOfA);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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