类模板使用自定义数据类型

#include <ostream>
#include <iostream>
using namespace std;

//Array.h
template <typename T, int size>
class Array{
public:
    Array();
	bool push(T elem);
	void display();
private:
    T *m_pArr;
	int m_iSize;
	int m_iLength;
};

template <typename T, int size>
Array<T,size>::Array ()
{
    m_iSize = size;
	m_iLength = 0;
	m_pArr = new T[m_iSize];
}

template <typename T, int size>
void Array<T,size>::display()
{
    for (int i = 0; i < m_iLength; i++)
	{
    cout << m_pArr[i] << endl;
	}
}

template<typename T, int size>
bool Array<T,size>::push(T elem)
{
    if (m_iLength >= m_iSize)
    {
		return false;
	}

    m_pArr[m_iLength]=elem;
	m_iLength++;
    return true;
}
//Cordiante.h
class Coordinate {
    friend ostream& operator<<(ostream &out, Coordinate &coor);
public:
    Coordinate(int x = 0, int y = 0);
private:
    int m_iX;
    int m_iY;
};

Coordinate::Coordinate(int x , int y )// 不能写(int x = 0, int y = 0)
{
    m_iX = x;
    m_iY = y;
}

ostream &operator<<(ostream &out, Coordinate &coor)
{
	out << coor.m_iX << "," << coor.m_iY << endl;
    return out;
}

main(){
    Array<Coordinate, 10> arr3;
	Coordinate coor1(3,5);
	Coordinate coor2(2,8);
	arr3.push(coor1);
	arr3.push(coor2);
	arr3.display();
    system("pause") ;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值