原创 linux下c++ lesson15 类模板

本文深入探讨了C++中模板类的使用,包括类模板的基本语法、继承与模板类的结合、模板类的声明与定义分离,以及静态成员在模板类中的特性。通过具体示例,展示了如何创建和使用模板类,以及模板类在继承和多态中的应用。

1-类模板.cpp

#include <iostream>

using namespace std;

template <typename T, typename U>
class Test
{
private:
	T a;
	U b;
public:
	Test(T a, U b)
	{
		this->a = a;
		this->b = b;
	}
	void show()
	{
		cout << a << " " << b << endl;
	}
};

int main()
{
	Test<int, char> t(1, 'a');   //类模板创建对象一定要显式调用
	t.show();

	return 0;
}

2-继承.cpp

#include <iostream>

using namespace std;

template <typename T>
class Parent
{
protected:
	T a;
public:
	Parent(T a)
	{
		this->a = a;
	}
	void show()
	{
		cout << a << endl;
	}
};

class Child : public Parent<int>   //模板类派生普通类  继承的同时对基类实例化
{
public:
	Child(int a) : Parent(a)
	{
		
	}
	void show()
	{
		cout << a << endl;
	}
};

template <typename T, typename U>
class Child2 : public Parent<T>   //模板类派生模板类  继承的同时不需要对Parent实例化
{
private:
	U b;
public:
	Child2(T a, U b) : Parent<T>(a)
	{
		this->b = b;
	}
	void show()
	{
		cout << this->a << " " << b << endl;
	}
};

int main()
{
	Child c1(1);
	c1.show();

	Child2<int, double> c2(1, 1.11);
	c2.show();

	return 0;
}

3-模板类声明.cpp

#include <iostream>

using namespace std;

template <typename T>
class Test
{
private:
	T a;
public:
	Test(T a);
	void show();
	~Test();
};

template <typename T>
Test<T>::Test(T a)     //Test<T>表示Test是模板类,不是普通类
{
	this->a = a;
}

template <typename T>
void Test<T>::show()
{
	cout << a << endl;
}

template <typename T>
Test<T>::~Test()
{
	
}

int main()
{
	Test<int> t(1);
	t.show();

	return 0;
}

4-static.cpp

#include <iostream>

using namespace std;

template <typename T>
class Test
{
private:
	T a;
public:
	static int count;
public:
	Test(T a)
	{
		this->a = a;
		count++;
	}
};

template <typename T>
int Test<T>::count = 0;

int main()
{
	Test<int> t1(1);
	Test<int> t2(1);
	Test<int> t3(1);
	Test<int> t4(1);
	Test<int> t5(1);

	Test<char> t6('a');
	Test<char> t7('a');
	Test<char> t8('a');

	cout << Test<int>::count << endl;
	cout << Test<char>::count << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值