如何在另一个类中创建对象?

时间:2016-09-15 14:13:05

标签: c++ class templates

我有这段代码。

#include "Stack.h"

template <class dataType>
class Queue2{

public:
    Queue2(int size);

    bool push(int data);
    bool pop(int &data);

    bool isEmpty();
    bool isFull();

    bool top(int &data);

    ~Queue2();
};

template <class dataType>
Queue2<dataType>::Queue2(int size = 10) : Stack <dataType> obj1(size), Stack <dataType> obj2(size) {//here i am facing an error. how can i fix it

}

我有一个带有这样构造函数的模板类 Stack

Stack(int size=10);

现在我想在 Queue2 类中创建 Stack 类的两个对象。

1 个答案:

答案 0 :(得分:1)

如果您为Queue2类提供了两个私有Stack成员,则可以在构造函数初始化中初始化它们,并单独访问它们:

class Queue2{
    Stack<dataType> left,right;
public:
    Queue2(int size);
    /* ... */

然后将构造函数定义为:

template<typename dataType>
Queue2<dataType>::Queue2(int size = 10)
  : left(size), right(size) {}
相关问题