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

How to create objects inside another class?

本文关键字:创建对象 另一个      更新时间:2023-10-16

我有这个代码。

#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类的对象。

如果你给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) {}