在另一个类中调用一个类(队列)的方法

calling the method of a class (queue) inside another class

本文关键字:一个 方法 队列 另一个 调用      更新时间:2023-10-16

node.h

--用于创建主机

 // host declaration
class Host : public Node {
    public:
        Host(uint32_t id, double rate, uint32_t queue_type, uint32_t host_type); // constructor
        Queue *queue; // queue to store the packets
        int host_type;
 };

queue.h

--队列声明,使用deque 实现

class Queue {
    public:
        Queue(uint32_t id, double rate, uint32_t limit_bytes, int location); // default constructor
        virtual void enque(Packet *packet); // I want to call this function 
};

main.cpp

--创建对象并尝试将数据包推送到主机中的队列的主程序

# include all the .h files
using namespace std;

int main()
{
Packet P1(20.4, 1, 0, 64); // creating a packet, not shows for simplicity
Host H1(0, 20.4,1, 0);     // creating my host  
H1.queue->enque(P1*); // This is where I get error 
                      // "invalid pointer".  I want to push the  
                      //packet P1 to the queue in the host, 
                      //I am not sure how to do it.  
return 0;
}

非常感谢您的帮助。谢谢,

您需要使用H1.queue->enque(&P1);。这取自动变量P1地址

但请记住,&P1仅在P1在范围内时有效。在生产代码中,您可能希望使用new创建一个Packet实例,并将其用作enque的参数。