在类构造函数中动态定义Stack,它是私有成员
Defining Stack dynamically in class constructor, which is private member
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
}
现在的问题是,当我编译它的错误出现,说"结构需要在左侧。或者。*"
我测试堆栈类在主要通过创建对象的结构和推入堆栈和弹出的工作!这意味着我的堆栈类工作正常。
我知道这个错误发生时,我们试图调用构造没有提供所需的参数,但我给出了值,所以为什么这个错误发生。
要修复编译器错误,您有两个选项,如我在评论中提到的:
- 将
stack* myData;
堆叠到myData;
- 将
myData.push(u);
更改为myData->push(u);
首选设计
要使第一个选项工作,你应该使用构造函数的成员初始化列表:
class uses{
private:
stack myData;
public:
uses(int len) : myData(len) {
}
};
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 成员数据在stack实例上覆盖
- 'stack::n':无法访问类 'stack' 中声明的私有成员
- 错误:'class std::stack<>'没有名为 'pop_back' 的成员
- 在循环内为类成员声明线程时,需要解释HEAP和STACK
- 在类构造函数中动态定义Stack,它是私有成员