c++ 模板类的 友元函数
2024-09-07 02:49:05
#pragma once
#include <iostream> template <class T>
class stack
{
template <class Ty>
friend std::ostream& operator<<(std::ostream& os, const stack<Ty>& s);
public:
explicit stack<T>(int maxSize);
stack<T>(const stack<T>& s);
stack<T>(stack<T>&&) = delete;
stack<T>& operator=(const stack& s);
stack<T>& operator=(stack<T>&&) = delete;
~stack<T>(); void push(T e);
bool pop(T& e);
bool getTop(T& e) const; bool isEmpty() const;
int getNumElems() const; private:
T* elems;
int top;
int maxSize;
void overflowProcess();
}; template <class T>
std::ostream& operator<<(std::ostream& os,const stack<T>& s)
{
for (int i = ; i <= s.top; i++)
{
std::cout << s.elems[i] << " ";
}
return os;
} template <class T>
stack<T>::stack(int maxSize_): top(-), maxSize(maxSize_)
{
this->elems = new T[this->maxSize];
} template <class T>
stack<T>::stack(const stack<T>& s)
{
this->top = s.top;
this->maxSize = s.maxSize;
this->elems = new T[this->maxSize];
memcpy_s(this->elems, sizeof(T) * maxSize, s.elems, sizeof(T) * maxSize);
} template <class T>
stack<T>& stack<T>::operator=(const stack& s)
{
if (this == &s) return *this;
if (this->elems != nullptr)delete[] elems;
this->top = s.top;
this->maxSize = s.maxSize;
this->elems = new T[maxSize];
memcpy_s(this->elems, sizeof(T) * maxSize, s.elems, sizeof(T) * maxSize);
return *this;
} template <class T>
stack<T>::~stack()
{
if (this->elems != nullptr)
delete[] elems;
} template <class T>
void stack<T>::push(T e)
{
if (this->top == maxSize - )
{
overflowProcess();
}
this->elems[++top] = e;
} template <class T>
bool stack<T>::pop(T& e)
{
if (!isEmpty())
{
e = this->elems[top--];
return true;
}
return false;
} template <class T>
bool stack<T>::getTop(T& e) const
{
if (!isEmpty())
{
e = elems[top];
return true;
}
return false;
} template <class T>
bool stack<T>::isEmpty() const
{
return top == - ? true : false;
} template <class T>
int stack<T>::getNumElems() const
{
return top + ;
} template <class T>
void stack<T>::overflowProcess()
{
T* new_elems = new T[maxSize + maxSize / ];
memcpy_s(new_elems, sizeof(T) * maxSize, this->elems, sizeof(T) * maxSize);
delete[] elems;
this->elems = new_elems;
}
代码长;懒得剪。。。。一个具备基本功能的栈类;可以直接使用
里面用到了: 模板友元函数 在类外定义的前面要加上template<class Ty> 以示区分
因此: 模板友元函数:类内定义 无需 template<class Ty> /////其实这个还不确定,下次试试就知道了
类内声明,类外定义:需要tempalte<class Ty>
最新文章
- 上个项目的一些反思 I
- 【NoSql】Redis
- nodejs - 如何完全更新
- Linux文件I/O学习
- 读取redis中的数据时出现:MISCONF Redis is configured to save RDB snapshots
- Asp.Net Mvc5 之Controller
- Touch Punch在移动设备上面增加jQuery UI的触摸支持|Jquery UI 支持移动端 触摸滑动等
- 2.请尝试安装和配置JDK,并给出安装、配置JDK的步骤。
- 004-Python字符串
- eclipse 标签标题乱码解决方法
- jdbcTemplate的queryForList
- UsernamePasswordAuthenticationToken
- LeetCode 98 验证二叉搜索树
- 2955 ACM 杭电 抢银行 01背包 乘法
- 问题处理:PROCESS一个domain节点起不来
- 【转】在64位windows下使用instsrv.exe和srvany.exe创建windows服务
- 3.10 Templates -- Development Helpers
- C#高级编程 (第六版) 学习 第四章:继承
- HttpClient POST 的 UTF-8 编码问题
- MyEclipse 相关配置操作、问题处理及快捷键说明