- 类模板:
- 类模板不可以使用自动类型推导,只能用显示指定类型,函数可以使用自动类型推导
- 类模板中 可以有默认参数
#include<iostream>
#include<string>
using namespace std;
template<class type_name = string, class type_age = int>
//template<class type_name , class type_age>
class person {
public:
person(type_name name,type_age age) {
this->name = name;
this->age = age;
}
void showInfo() {
cout << this->name << " " << this->age << endl;
}
type_name name;
type_age age;
};
class person1 {
public:
void show1() {
cout << "show1" << endl;
}
};
class person2 {
public:
void show2() {
cout << "show2" << endl;
}
};
template<class T>
class person3 {
public:
void show1() {
obj.show1();
}
void show2() {
obj.show2();
}
T obj;
};
void dowork1(person<string,int>&p) {
p.showInfo();
}
template<class t1, class t2>
void dowork2(person<t1,t2>&p) {
p.showInfo();
}
template<class t>
void dowork3(t &p) {
p.showInfo();
cout << "t的数据类型: " << typeid(t).name() << endl;
}
void test() {
person<> p("Tom", 21);
//person<string,int> p("Tom",21);
p.showInfo();
person3<person2> p3;
p3.show2();
dowork1(p);
dowork2(p);
dowork3(p);
}
int main() {
test();
system("pause");
return EXIT_SUCCESS;
}
类模板碰到继承的问题以及解决、类模板中的成员函数类外实现
#include<iostream>
using namespace std;
template<class T>
class father {
public:
T num;
};
template<class t1,class t2>
class son :public father<t2> {
public:
son(t1 n, t2 m);
/*son(t1 n,t2 m) {
this->n = n;
this->num = m;
cout << typeid(t1).name() << " " << this->n << endl;
cout << typeid(t2).name() << endl;
}*/
t1 n;
void print();
};
template<class t1,class t2>
son<t1,t2>::son(t1 n, t2 m) {
this->n = n;
this->num = m;
cout << typeid(t1).name() << " " << this->n << endl;
cout << typeid(t2).name() << endl;
}
template<class t1,class t2>
void son<t1 ,t2>::print() {
cout << this->num << this->n << endl;
}
void test() {
son<int, double> s1(1,2);
s1.print();
}
int main() {
test();
system("pause");
return EXIT_SUCCESS;
}
类模板碰到友元的问题以及解决
#include<iostream>
#include<string>
using namespace std;
template<class T1, class T2>
class person;
template<class T1, class T2>
void getInfo(person<T1, T2>& p);
template<class T1,class T2>
class person {
friend void getInfo<>(person<T1, T2>& p);
friend void print(person<T1,T2>&p) {
cout << p.name << " " << p.age << endl;
}
private:
T1 name;
T2 age;
public:
person(T1 name, T2 age) {
this->name = name;
this->age = age;
}
};
template<class T1, class T2>
void getInfo(person<T1, T2>& p) {
cout << p.name << " " << p.age << endl;
}
void test() {
person<string ,int> p("Tom",21);
getInfo(p);
print(p);
}
int main() {
test();
system("pause");
return EXIT_SUCCESS;
}