#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));
}
数据是怎么导入的。
类模板实例化时,如果模板类型是另一个类,那是怎么运行的?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- threenewbee 2020-01-17 23:43关注
参考:https://www.cnblogs.com/share-happy-everyday/p/9354540.html
之前的回答详细写出了代码然而没有得到采纳,希望你问题解决能采纳,这样才能更详细回答你的问题
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
- ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
- ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
- ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
- ¥20 腾讯企业邮箱邮件可以恢复么
- ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
- ¥15 错误 LNK2001 无法解析的外部符号
- ¥50 安装pyaudiokits失败
- ¥15 计组这些题应该咋做呀
- ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?