#include<String>
struct Person
{
std::string name;
int age;
Person(std::string n, int a) :name(n), age(a)
{
}
Person()
{
}
};
namespace VGP130
{
template<typename T, size_t n>
class Stack
{
public:
explicit Stack() :top(-1), size(n)
{
}
~Stack() = default;
bool push(const T& a)
{
if (!isFull())
{
data[++top] = a;
return true;
}
return false;
}
bool isFull() const
{
return top == size - 1;
}
bool isEmpty()const
{
return top == -1;
}
bool pop(T& ret)
{
if (isEmpty())
return false;
ret = data[top--];
return true;
}
void print()
{
std::cout << "Stack: ";
for (int i = 0; i <= top; ++i)
std::cout << data[i] << std::endl;
std::cout << std::endl;
}
private:
T data[n];
int top;
size_t size;
};
}
#include<iostream>
#include "Person.h"
#include "Stack.h"
using namespace std;
using namespace VGP130;
int main()
{
Stack<Person, 5> personStack;
for (int i = 0; i < 5; ++i)
{
personStack.push(Person("what",2));
}
Person pValue{};
for (int i = 0; i < 5; ++i)
{
if (personStack.pop(pValue))
cout << "Top of peraonStack: " << pValue.name <<" "<<pValue.age <<endl;
else
cout << "pop from empty stack" << endl;
}
system("pause");
}
stack 是模板类,在main函数里实例化的时候,模板类型T是另一个结构体
Person
Stack<Person, 5> personStack
请问下面的代码是如何实现的:
for (int i = 0; i < 5; ++i)
{
personStack.push(Person("what",2));
}
数据是怎么导入的。
参考:https://www.cnblogs.com/share-happy-everyday/p/9354540.html
这个问题很难形象的解释~
首先你要知道 模板类 的概念;例如 你这里写的 Stack<T,n>
;在我们没有写 Stack<Person,5> personStack;
,
上面的Stack都是没有实际意义的,但是如果写了Stack<Person,5> personStack;
这句声明的话,就等于你把上面的所有代码重新写了一遍,并且把所有的 T
用 Person
代替
所有的n
用5代替;
那么你的 push
函数的函数原型就变成了:
bool push(const Person &a)
{
if (!isFull())
{
data[++top] = a;
return true;
}
return false;
}
此时我们继续分解这个语句:
personStack.push(Person("what",2));
//等效于
Person bob = Person("what",2);
personStack.push(bob);
那至于这个 Person("what",2);
就是**_Person
_**的 构造函数,
不知道这么说你能不能理解?
personStack.push(Person("what",2));中
personStack是栈的一个实例,即类的一个对象;
Person("what",2)调用Person的构造函数,定义了一个结构体变量,
bool push(const Person &a)的形参a是引用,就是这个结构体变量的别名;
const作用就是在push函数中a不能被修改;
在push函数中,data[++top] = a;
push函数结束,这个结构体变量被释放。
循环5次,重复上述操作,压入栈中5个结构体变量。