0

我有一个设计问题。我被要求为某个问题计划一个设计,我需要一些列表,还有一个队列(我需要自己创建,不允许使用 STL)。为了使实现更高效,我考虑创建一个通用列表,如下所示: 创建一个节点,其中包含一个指向“数据”的指针,一个空类。然后,任何我想创建一个列表或队列的类(最后一句话在语法上是否正确?),我只会让它成为数据的子类。这是制作通用列表的唯一方法(我认为),因为我们不允许使用 void*。当我想在某个列表中使用某个类的某个方法时,问题就开始了。我不能这样做,因为“数据”不知道该功能。在 Data 中创建一个虚函数是反逻辑和丑陋的,我们' re 也不允许使用任何向下转换。有没有办法使用通用 ADT 来解决这个问题?还是我必须创建特定列表?非常感谢!编辑:我们也不允许使用模板。

4

1 回答 1

0

About the list and the queue, maybe you can adopt the same approach taken by the STL: just create the list, and then stack, as an adaptor of the list in which you only push and pop from the end.

About those contraints, which seems to be draconian, don't I suppose that the objective is for you to use templates?

Instead of creating and empty class, which if does not contain any method does not serve you at all, use a template as in the following example:

template<typename T>
class List {

    class Node {
    public:
        Node(T* d)
            { data.reset( new Data( d ) ); }
        T * getData()
            { return data; }
        Node * getSig()
            { return sig; }
    private:
        std::auto_ptr<T> data;
        Node * sig;
    };

    List()...
// Lots of more things...
};

You can find more info here:

http://www.cplusplus.com/doc/tutorial/templates/

Hope this helps.

于 2012-05-28T15:26:30.610 回答