Container

Container.h

#ifndef _CONTAINER_H_
#define _CONTAINER_H_
#include <iostream>

template <typename T>
class Container {
	public:
		virtual T& operator[](int i) = 0;
		virtual int size() const = 0;
		virtual ~Container() {}
};

#endif

Vector_Container

#ifndef _VECTOR_CONTAINER_H_
#define _VECTOR_CONTAINER_H_
#include "Container.h"
#include <vector>
#include <initializer_list>

template <typename T>
class Vector_Container : public Container<T>{
	public:
		Vector_Container(std::initializer_list<T> lst): vec{lst} {}
		~Vector_Container() {}
		
		T& operator[](int i);
		int size() const;
	private:
		std::vector<T> vec;
};

template <typename T>
T& Vector_Container<T>::operator[](int i)
{
	return vec[i];
}

template <typename T>
int Vector_Container<T>::size() const
{
	return vec.size();
}

template <typename T>
std::ostream& operator<<(std::ostream& os,Vector_Container<T>& vc)
{
	os << "vector [";
	for(int i=0; i<vc.size(); i++)
	{
		os << vc[i];
		if (i<vc.size()-1)
			os << ",";
	}
	os << "]";
	return os;
}

#endif

List_Container

#ifndef _LIST_CONTAINER_H_
#define _LIST_CONTAINER_H_
#include "Container.h"
#include <list>
#include <initializer_list>
#include <stdexcept>

template <typename T>
class List_Container : public Container<T>{
	public:
		template <typename U>
		friend std::ostream& operator<<(std::ostream& os,List_Container<U>& lc);
		List_Container(std::initializer_list<T> ilst): lst{ilst} {}
		~List_Container() {}
		
		T& operator[](int i);
		int size() const;
	private:
		std::list<T> lst; 
};

template <typename T>
T& List_Container<T>::operator[](int i)
{
	for(auto& x: lst)
	{
		if (i==0) return x;
		i--;
	}
	throw std::out_of_range("List container");
}

template <typename T>
int List_Container<T>::size() const
{
	return lst.size();
}

template <typename T>
std::ostream& operator<<(std::ostream& os,List_Container<T>& lc)
{
	os << "List: [";
	int i = 0;
	for(auto x : lc.lst)
	{
		i++;
		os << x;
		if (i<lc.size())
			os << ",";
	}
	os << "]";
	return os;
}

#endif

makeFile.cpp

#include "Vector_Container.h"
#include "List_Container.h"

template <typename T>
void use(Container<T>& c)
{
	std::cout << c << std::endl;
}

int main()
{
	Vector_Container<int> vc{1,2,3,4,5};
	List_Container<int> lc{1,2,3,4,5};
	std::cout << vc << std::endl;
	std::cout << lc << std::endl;
	//use(vc);
	//use(lc);
}

为什么不能执行use()呢?是因为operator<<不是Container,而且也不是其实现类的成员函数,不能通过通过基类指针或引用调用到子类的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值