在类构造函数中动态定义Stack,它是私有成员

Defining Stack dynamically in class constructor, which is private member

本文关键字:成员 Stack 构造函数 动态 定义      更新时间:2023-10-16

Friends我定义了一个堆栈类,它使堆栈成为一个结构,另一个类使用堆栈(动态创建),如下

struct A{
   int a;
   .....
};
class stack{
   private:
     int head,max;
     A* data;       // pointer of structure 'A'
   public:
     stack(int length){   // constructor to allocate specified memory
       data = new A[length];
       head = 0;
       max = length;
     }
    void push(A){....}    //Accepts structure 'A'
    A pop(){.......}      //Returns structure 'A'
};
//Another class which uses stack
class uses{ 
   private:
     stack* myData;
     void fun(A);    //funtion is accepts structure 'A'
     ..........
   public:
     uses(int len){
        myData = new stack(len);  //constructor is setting length of stack 
    }
};
void uses::fun(A t){
  A u=t;
 ....done changes in u
 myData.push(u);    //error occurs at this line
}

现在的问题是,当我编译它的错误出现,说"结构需要在左侧。或者。*"

我测试堆栈类在主要通过创建对象的结构和推入堆栈和弹出的工作!这意味着我的堆栈类工作正常。

我知道这个错误发生时,我们试图调用构造没有提供所需的参数,但我给出了值,所以为什么这个错误发生。

要修复编译器错误,您有两个选项,如我在评论中提到的:

  1. stack* myData;堆叠到myData;
  2. myData.push(u);更改为myData->push(u);

首选设计

要使第一个选项工作,你应该使用构造函数的成员初始化列表:

class uses{ 
private:
    stack myData;
public:
    uses(int len) : myData(len) {
    }
};