这里是头文件代码,stack.h:
#include <iostream>
using namespace std;
//template <class T> struct stackNode;
//template <class T>
struct stackNode {
int item;
stackNode *Next;
stackNode *Prev;
//stackNode *Temp;
};
class stackClass {
public:
stackClass();
stackClass(const stackClass &right);
~stackClass();
stackClass &operator=(const stackClass &right);
int counter;
int StackIsEmpty(void);
//stackNode *origptr;
void push( int item, bool &success);
int pop(void);
int GetStackTop(void);
protected:
stackNode *GetStackTopPtr(void);
private:
stackNode *Top;
stackNode *Current;
//stackNode *origptr;
//stackNode<T> *Next;
};
这里是实现文件,stack.cpp:
#include "stack.h"
//constructor
stackClass::stackClass(){
Top = NULL;
int counter = 0;
}
//copy constructor
stackClass::stackClass(const stackClass &right){
if (right.Top == NULL){
Top = NULL;
counter = 0;
}
else {
stackNode * origptr = right.GetStackTopPtr;
stackNode * currptr;
Top = new stackNode;
currptr = Top;
while(origptr->Next != NULL){
currptr->item = origptr->item;
origptr = origptr->Next;
currptr->Next = new stackNode;
currptr->Next->item = origptr->item;
currptr = currptr-> Next;
}
currptr->Next = NULL;
}
}
//Destructor
stackClass::~stackClass(){
while (Top != NULL){
pop();
}
}
//push
void stackClass::push(int item, bool &success){
success = false;
if (Top == NULL){
Top = new stackNode;
Top -> item = item;
Top -> Next = NULL;
Top -> Prev = NULL;
Current = Top;
counter++;
success = true;
}
else {
stackNode * Temp = new stackNode;
Current -> Next = Temp;
Temp -> Prev = Current;
Temp -> Next = NULL;
Current = Temp;
Current -> item = item;
counter++;
success = true;
}
}
int stackClass::pop(void){
if (Top == NULL){
cout<<"Stack is empty"<<endl;
}
else if (counter == 1){
Top = NULL;
delete Current;
counter--;
}
else if(counter > 1){
Current -> Prev -> Next = NULL;
Current = Current -> Prev;
stackNode * Temp = Current -> Next;
delete Temp;
counter--;
}
}
int stackClass::StackIsEmpty(void){
if (counter == 0)
return 1;
else
return 0;
}
int stackClass::GetStackTop(void){
int item = Top->item ;
return item;
}
stackNode *stackClass::GetStackTopPtr(void){
return Top;
}
问题来了
stack.cpp: In copy constructor ‘stackClass::stackClass(const stackClass&)’:
stack.cpp:19:31: error: cannot convert ‘stackClass::GetStackTopPtr’ from type ‘stackNode* (stackClass::)()’ to type ‘stackNode*’
我不知道为什么编译器会提示,似乎在有问题的行中,在 stack.cpp 的第 19 行中,right.GetStackTopPrt
会返回一个 stackNode *
类型,它应该很好地分配给左侧的 stackNode*
。
如果您知道问题出在哪里,请提供帮助。谢谢!
最佳答案
你正在尝试设置
stackNode * origptr = right.GetStackTopPtr;
其中左侧是 stackNode
指针,右侧是函数 GetStackTopPtr
。我想你是想写:
stackNode * origptr = right.GetStackTopPtr(); // Note the parentheses!
请记住,编译器非常擅长识别类型,并且几乎总是对这些事情。不要假设编译器是错误的,首先要查找您犯的错误!
关于c++ - 由于类型不匹配,无法将一个指针分配给另一个指针,或者编译器这样说,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15715488/