C++最强大的特性之一——模板Templates(下:模板类)

 

本文为作者EricNTH的原创博客,允许转载但请务必注明出处!

嗨,大家好,我们又见面了,今天我们来继续谈谈C++模板——模板类。

目录

1.C++最强大的特性之一——模板Templates(上:模板函数)—原创
2.C++最强大的特性之一——模板Templates(下:模板类)—原创

好了,现在公布上次作业的答案!
(由于还没有人评论【哭】,没法放各位的啊,不过只要后面有人做了我一定会第一时间放上去)
——————————————————————————————

模板类的声明

模板类的声明与模板函数相差不多,下面举个栗子:

template <typename _Tp>
class MyClass
{
	public:
	//Functions&declarations
	protected:
	//Functions&declarations
	private:
	//Functions&declarations
}

一切都是如此的相似,那么我们来看一下声明吧。

MyClass <int> myclass1;

很像吧,几乎一样?没错!
唯一的区别就是不能自动补充类型(如int)。

其实,STL中的一切容器,都是模板类!(STL的算法也基本都是模板函数)
For example:

vector<int>;
set<int>;
map<char*, int>;
bitset<4>;

(纠个错:bitset并不是STL容器,是一个STL实用类)
大家可能注意到了,< >之间可能不止有一个typename,而且还可以有数字这些东西!
我们来看一下vector的声明。

template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
    class vector : protected _Vector_base<_Tp, _Alloc>

没错,< >之间也可以像函数一样,使用默认值!
那为什么要用模板呢?

  • 函数的参数中不能有typename。
  • STL用的也是模板,有样学样【哈哈】
  • 在ANSI C++标准中,所有最新版本的编译器都全面支持(当然函数也是)。
  • 别忘了,还有模板类!这个肯定时必用不可了。

注意:以上讲的大部分都同样适用于模板函数(如设默认值等)。

亲自尝试吧!来自己写一个模板类Stack!

template <typename T>
	class Stack {
		private:
			int len;
			int ptr;
			T sta[3000];
			bool Good;
		public:
			Stack() {
				len = 0;
				ptr = -1;
				Good = true;
			}
			~Stack() {
				clear();
				Good = false;
				ptr = -1;
				len = 0;
			}
			bool CheckGood (void) {
				return Good;
			}
			void push(T pushed_data) {
				if (!Good) {
					return;
				}
				ptr++;
				sta[ptr] = pushed_data;
			}
			void pop(void) {
				ptr--;
				if (ptr < -1) {
					MessageBox(NULL, "Fatal Error --- Warning before crashing\nAdvice: Close this file and edit and compile again.\nOr this program may CRASH.\nError name: underflow.\nIn function: pop.", "my_header.hpp", 18);
					Good = false;
				}
				if (!Good) {
					return;
				}
			}
			T visit(int index) {
				if ((index - 1) > ptr) {
					MessageBox(NULL, "Failed to visit!", "my_header.hpp", 18);
				}
				if (index < 1 || (index - 1) > ptr)  {
					MessageBox(NULL, "Fatal Error --- Warning before crashing\nAdvice: Close this file and edit and compile again.\nOr this program may CRASH.\nError name: underflow.\nIn function: visit.", "my_header.hpp", 18);
					Good = false;
				} 
				return sta[index - 1];
			}
			int size(void) {
				srand(time(0));
				if (Good) {
					return ptr + 1;
				}
				return rand();
			}
			void clear() {
				ptr = -1;
				len = 0;
				Good = false;
			}
	};

基本都很简单,大家应该看得懂(我自认为【笑】),至于MessageBox函数,是用来弹出错误信息的,用法大家可以参见这篇博客:Windows API 教程:MessageBox函数详解

The end

好了,有关于模板我们就讲到这里了。模板很强大,很好用,但绝不简单。需要大家认真练习,琢磨,思考,有任何问题(很有可能)一定要联系我,或看其他小伙伴们的博客。这里再和大家说一下我的联系方式,我看到后一定尽快回复!

  • 直接再评论区回复,我看得到
  • 邮箱:eric_ni2008@163.com
  • 或私信我,我没有设置任何联系方式的权限,大家可以自由选择!

好了,今天也不早了,模板也讲完了,我们下期再见!

本文为作者EricNTH的原创博客,允许转载但请务必注明出处!

返回上一篇:C++最强大的特性之一——模板Templates(上:模板函数)

喜欢麻烦点个赞或加个关注呗~

posted @ 2020-02-27 18:08  EricNTH  阅读(227)  评论(0编辑  收藏  举报