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;
}

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

1007

被折叠的 条评论
为什么被折叠?



