//类模板 派生 1 普通类 2派生类#include<iostream>
using namespace std;
template <typename T>
class A
{
public:A(T a){
this->a = a;}voidprintA(){
cout <<"a: "<< a << endl;}
protected:
T a;};//派生普通类,子类从模板类继承的时候,需要让编译器知道 父类的数据类型具体是什么
class B : public A<int>{
public:B(int a,int b):A<int>(a){
this->b = b;}voidprintB(){
cout <<"a: "<< a <<" b: "<< b << endl;}
private:int b;};//派生 派生类,两个模板具体类型都暂不知道
template <typename T>
class C : public A<T>{
public:C(T a, T c):A<T>(a){
this->c = c;}voidprintC(){//cout << "a: " << a << " c: " << c << endl; //此时a类型不确定无法输出?
cout <<"c: "<< c << endl;}
protected:
T c;};intmain02(){
B b1(1,2);
b1.printB();//A<double> a1(2.3);
C<int>c1(2,3);
c1.printC();
c1.printA();return0;}
类模板函数在类外部
//总结:友元函数只用来进行 左移 右移操作符重载,不要滥用,特别是在类模板中#include<iostream>
using namespace std;//模板函数在 类内部 或 类外部 或.h和.cpp分开
template <typename T>//类模板
class Complex
{
friend ostream& operator<<<T>(ostream& out, Complex& c3);//重载<<//重要:模板类中友元函数在类外定义需要在声明时在函数名后加<T>
public:Complex(T a, T b);voidprintCom();
Complex operator+(Complex& c2);//重载+
private:
T a;
T b;};
template <typename T>
Complex<T>::Complex(T a, T b)//类模板里面的构造函数{
this->a = a;
this->b = b;}
template <typename T>void Complex<T>::printCom(){
cout <<"a: "<< a <<" b: "<< b << endl;}//因为类模板类型是不确定的,所以在类外都要带<T>,函数体内属于类内部,<T>可带可不带//检查需不需要带<T>,主要检查函数三要素:名称 参数 返回值
template <typename T>
Complex<T> Complex<T>::operator+(Complex<T>& c2)//重载+{
Complex tmp(a + c2.a, b + c2.b);return tmp;}
template <typename T>
ostream& operator<<(ostream& out, Complex<T>& c3)//重载<<{
out << c3.a <<"+"<< c3.b <<"i"<< endl;return out;}intmain(){
Complex<int>c1(1,2);
Complex<int>c2(3,4);
Complex<int> c3 = c1 + c2;
cout << c3;return0;}