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

时间:2015-05-14 20:13:04

标签: c++ dynamic stack

朋友我定义了一个堆栈类,它构建了一个结构的堆栈,另一个类使用了堆栈(动态创建),如下所示

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的对象来测试main中的堆栈类,并将其推入堆栈并使用poped工作!这意味着我的堆栈类工作正常。

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

1 个答案:

答案 0 :(得分:2)

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

  1. myData;更改为堆叠myData.push(u);
  2. myData->push(u);更改为class uses{ private: stack myData; public: uses(int len) : myData(len) { } };
  3. 优先设计是第一选择。

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

    char code  *text_to_compare = "TesT";     
    char code  *dictionary = "TesTT,Tes,Tes,TesT.";
    
相关问题