看了视频学了c++之“栈”的一些内容,自己编辑之后发现一个问题,在main函数中(点击此跳到main函数)测试除了问题。
我首先声明了五个Person类的对象,将它们作为实参传递测试时:(如下图)
我尝试着删除一个值时(如下图)
这是我有尝试插入一个值是却出现了问题(如下图)
问题出在何处呢?
以下是代码
#include<iostream>
#include<string>
using namespace std;
#include<ostream>
//Person类
class Person
{
friend ostream &operator<<(ostream &out, Person per);
private:
string Name;
string Sex;
int Age;
string Addr;
public:
bool operator==(Person per);
Person(string N = "XXX", int A = 18, string S = "男", string Ad = "贵州")
{
Name = N;
Age = A;
Sex = S;
Addr = Ad;
}
};
ostream &operator<<(ostream &out, Person per)
{
out << "姓名:" << per.Name << "\t"
<< "年龄:" << per.Age << "\t" << "性别:"
<< per.Sex << "\t" <<
"地址:" << per.Addr << endl;
return out;
}
//
bool Person::operator==(Person per)
{
if (this->Addr == per.Addr&&this->Age == per.Age)
return true;
else
return false;
}
class Mystank
{
public:
Mystank(int m_myStank);
virtual ~Mystank();
void clearStank();//清除
bool StankEmpty() const;//判断是否为空
bool StankFull();//判断是否为满
int getStankLength();//获取长度
bool Enstank(Person *element);//插入一个值
bool Destank(Person *element);//删除一个值
void StankTravall();//遍历函数
private:
int m_stankLength;
int m_stankSize;
int m_iTail;
int m_iHead = 0;
Person *m_pStank;
};
Mystank::Mystank(int size)
{
m_stankSize = size;
m_stankLength = 0;
m_iTail = size-1;
m_pStank = new Person[m_stankSize];
}
Mystank::~Mystank()
{
delete []m_pStank;
m_pStank = NULL;
}
void Mystank::clearStank()
{
m_stankLength = 0;
}
bool Mystank::StankEmpty() const
{
return (m_stankLength == 0)? true : false;
}
bool Mystank::StankFull()
{
return (m_stankLength == m_stankSize) ? true : false;
}
int Mystank::getStankLength()
{
return m_stankLength;
}
bool Mystank::Enstank(Person *element)
{
if (StankFull())
{
return false;
}
m_pStank[m_iTail] = *element;
m_iTail--;
m_stankLength++;
return true;
}
bool Mystank::Destank(Person *element)
{
if (StankEmpty())
{
return false;
}
m_iTail++;
*element = m_pStank[m_iTail];
m_iHead++;
m_stankLength--;
return true;
}
void Mystank::StankTravall()
{
for (int i = m_iHead; i <m_stankLength +m_iHead; i++)
{
cout << m_pStank[i] << endl;
}
}
int main()
{
Mystank* mystank = new Mystank(5);
Person q1("张三", 18, "男", "江苏");
Person q2("李四", 17, "女", "贵州");
Person q3("王五", 20, "男", "北京 ");
Person q4("赵六", 21, "女", "上海");
Person q5("陈七", 21, "女", "东北");
mystank->Enstank(&q1);
mystank->Enstank(&q2);
mystank->Enstank(&q3);
mystank->Enstank(&q4);
mystank->Enstank(&q5);
mystank->StankTravall();
cout << "删除后:" << endl;
mystank->Destank(&q1);
cout << q1 << endl;
cout << endl;
mystank->StankTravall();
cout << "再插入后:" << endl;
mystank->Enstank(&q4);
mystank->StankTravall();
delete mystank;
mystank = NULL;
}