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

Defining Stack dynamically in class constructor, which is private member

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

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
}

现在的问题是当我编译它时出现错误 "Structure required on left side of . or .*"

我通过创建 Structure 的对象并推入堆栈并弹出来在 main 中测试堆栈 class,这有效!这意味着我的堆栈 class 工作正常。

我知道当我们尝试在不提供必需参数的情况下调用构造时会发生此错误,但我正在提供值,所以为什么会出现此错误。

要修复编译器错误,您有两种选择,如我的评论所述:

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

首选设计是第一个选项。

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

class uses{ 
private:
    stack myData;

public:
    uses(int len) : myData(len) {
    }
};