template.cpp

来自「自己写的c++实现的headfirst中的设计模式」· C++ 代码 · 共 100 行

CPP
100
字号
#include <iostream>

using namespace std;


template<class Object>
class Compare	//抽象类不可以实例化!不能=0
{
public:
	virtual bool operator ()(const Object& a,const Object& b)
	{
		return 1;
	}
};

template<class Object>
class IsMoreThan:public Compare<Object>	//这也得写<Object>...
{
public:
	bool operator ()(const Object& a,const Object& b)
	{
		return a>b;
	}
};

template<class Object>
class IsLessThan:public Compare<Object>
{
public:
	bool operator ()(const Object& a,const Object& b)
	{
		return a<b;
	}
};

template<class Object>
void one(const Object& a,const Object& b,Compare<Object>& c)
	//必须引用,否则拷贝构造后只保留父类信息,丢失对virtual的覆盖!
{
	if(c(a,b)) cout << a <<endl;
	else cout << b <<endl;
}

void template_main()
{
	IsMoreThan<int> big;
	IsLessThan<int> small;
	one(1,5,big);
	one(1,5,small);
	
	//one(1,5,IsMoreThan<int> );
}



/*
class Compare	
{
public:
	virtual bool operator ()(const int& a,const int& b)
	{
		return 1;
	}
};

class IsMoreThan:public Compare	//这也得写<Object>...
{
public:
	bool operator ()(const int& a,const int& b)
	{
		return a>b;
	}
};

class IsLessThan:public Compare
{
public:
	bool operator ()(const int& a,const int& b)
	{
		return a<b;
	}
};

void one(const int& a,const int& b,Compare& c)
{
	if(c(a,b)) cout << a <<endl;
	else cout << b <<endl;
}

int main()
{
	IsMoreThan a;
	IsLessThan b;
	one(1,5,a);
	one(1,5,b);
	
	return 0;
}
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?