通过 C++ 中的函数创建类的新句柄

creating a new handle to class through a function in c++

本文关键字:句柄 新句柄 创建 C++ 函数 通过      更新时间:2023-10-16

我不确定我的标题是否有意义。我正在尝试用 c++ 实现一个队列类。以下是我到目前为止的q.cpp课程

#include "q.h"
    q::q()
    {
        for(int i = 0; i < q::QUEUE_SIZE; i++) 
        {
            q::data[i] = '0';
        }
        q::front = q::rear = -1;
        printf(" YEA QUEUE HAS BEEN CREATED ");
    }
    q* q::createQueue()
    {
        return new q;
    }

现在在我的输出类 (main.cpp) 中,我希望能够通过 createQueue() 函数调用并返回当前队列类对象的句柄来创建新队列

像这样的东西

q* firstQueue = createQueue();
q* secondQueue = createQueue();

我在想我的主要构造函数 q() 需要私有,并且 createQueue 应该像工厂一样运行,所以我的 q.h 文件应该如下所示?

#ifndef Q_H
#define Q_H
#include <stdio.h>
class q
{
public:
    void destroy_queue(q* currentQueue);
    void enque_byte(q* currentQueue,unsigned char b);
    unsigned char deque_byte(q* currentQueue);
    static q* createQueue();
private:    
    static const int QUEUE_SIZE = 2048;
    unsigned char data[QUEUE_SIZE];
    int front, rear;
    q();
};
#endif // Q_H

然后我如何能够通过调用进行排队、取消排队操作

然后对任意数量的队列执行排队和取消排队操作,例如

enqueue(firstQueue,5);
dequeue(firstQueue);
enqueue(secondQueue,10);
..
..

并且不使用对象来调用它们

firstQueue->enqueue(...)

我对代码的组织有点困惑。希望有人能提供关于如何实现这种结构的见解?

你可以写简单的包装器,比如

void enqueue(q* obj, int x) {
    obj->enqueue(x);
}

然而,所有这些都没有多大意义;C++习语是使用对象和方法,除非你处于这个成语效果不佳的情况下(例如多方法),否则遵循它比反对它容易得多。