编译错误:passing ‘const LinkStack’ as ‘this’ argument discards qualifiers [-fpermissive]
解决方法:C++中const 引用的是对象时只能访问该对象的const 函数,因为其他函数有可能会修改该对象的成员,编译器为了避免该类事情发生,会认为调用非const函数是错误的。
函数末尾加const,表示不会修改该对象的成员。
// stack_node.h
#ifndef STACK_NODE_H
#define STACK_NODE_H
template<typename Type> class LinkStack;
template<typename Type> class StackNode
{
private:
friend class LinkStack<Type>;
StackNode(Type dt, StackNode<Type> *next=NULL) : m_data(dt), m_pnext(next){}
private:
Type m_data;
StackNode<Type> *m_pnext;
};
#endif // STACK_NODE_H
// link_stack.h
#ifndef LINK_STACK_H
#define LINK_STACK_H
#include "stack_node.h"
#include <iostream>
template<typename Type> class LinkStack
{
public:
LinkStack() : m_ptop(NULL){}
~LinkStack()
{
MakeEmpty();
}
public:
void MakeEmpty();
void Push(const Type item);
Type Pop();
Type GetTop() const;
void Print();
bool IsEmpty() const
{
return (m_ptop == NULL);
}
private:
StackNode<Type> *m_ptop;
};
template<typename Type> void LinkStack<Type>::MakeEmpty()
{
if(m_ptop == NULL)
{
exit(1);
}
StackNode<Type> *pdel = NULL;
while(m_ptop != NULL)
{
pdel = m_ptop;
m_ptop = m_ptop->m_pnext;
delete pdel;
}
}
template<typename Type> void LinkStack<Type>::Push(const Type item)
{
m_ptop = new StackNode<Type>(item, m_ptop);
}
template<typename Type> Type LinkStack<Type>::GetTop() const
{
if(IsEmpty())
{
std::cout << __FUNCTION__ << " error stack is empty " << std::endl;
exit(1);
}
return m_ptop->m_data;
}
template<typename Type> Type LinkStack<Type>::Pop()
{
if(IsEmpty())
{
std::cout << __FUNCTION__ << " error stack is empty " << std::endl;
exit(1);
}
StackNode<Type> *pdel = m_ptop;
m_ptop = m_ptop->m_pnext;
Type temp = pdel->m_data;
delete pdel;
return temp;
}
template<typename Type> void LinkStack<Type>::Print()
{
StackNode<Type> *pcursor = m_ptop;
std::cout << "buttom";
while(pcursor != NULL)
{
std::cout << "--->" << pcursor->m_data;
pcursor = pcursor->m_pnext;
}
std::cout << "--->top" << std::endl << std::endl << std::endl;
}
#endif // LINK_STACK_H
// main.cpp
#include <iostream>
#include "link_stack.h"
using namespace std;
int main(int argc, char *argv[])
{
LinkStack<int> stack;
int init[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17,19};
for(int i = 0; i < 10; i++)
{
stack.Push(init[i]);
}
stack.Print();
cout << stack.Pop() << endl;
stack.Print();
cout << stack.GetTop() << endl;
stack.Print();
cout << stack.Pop() << endl;
stack.Print();
stack.MakeEmpty();
stack.Print();
stack.Pop();
return 0;
}