C++类模板(十三)

32 篇文章 0 订阅
  1. 类模板:
    1. 类模板不可以使用自动类型推导,只能用显示指定类型,函数可以使用自动类型推导
    2. 类模板中 可以有默认参数
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值