c++ 类模板

函数模板和类模板

函数模板:

template < class T>
函数

类模板

template < class T>
class 类模板名{
};

#include<iostream>
using namespace std;

template <class T>
class A{
public:
    template <class T2>
    void Func(T2 t) {
        cout << t << endl;
    }  //成员函数模板
};

int main(){
    A<int> a;
    a.Func('c');  //成员函数模板Func被实例化
    a.Func("hello");
    system("pause");
    return 0;
}

在这里插入图片描述

类模板与函数模板区别

区别:

  1. 类模板没有自动类型推导的使用方式, 只能用显示指定类型方式
  2. 类模板在模板参数列表中可以有默认参数
#include <iostream>
#include <string>
using manespace std;

template<class NameType, class AgeType = int> 
class Person{
public:
	Person(NameType name, AgeType age){
		this->mName = name;
		this->mAge = age;
	}
	void showPerson(){
		cout << "name: " << this->mName << " age: " << this->mAge << endl;
	}
public:
	NameType mName;
	AgeType mAge;
};

//1、类模板没有自动类型推导的使用方式
void test01()
{
	// Person p("孙悟空", 1000); // 错误 类模板使用时候,不可以用自动类型推导
	Person <string ,int>p("孙悟空", 1000); //必须使用显示指定类型的方式,使用类模板
	p.showPerson();
}

2. 类模板在模板参数列表中可以有默认参数
void test02(){
	Person <string> p("猪八戒", 999); //类模板中的模板参数列表 可以指定默认参数
	p.showPerson();
}

int main() {
	test01();
	test02();
	system("pause");
	return 0;
}

类模板中成员函数创建时机

普通类中的成员函数一开始就可以创建

#include <iostream>
using namespace std;

class Person1{
public:
	void showPerson1(){
		cout << "Person1 show" << endl;
	}
};

class Person2{
public:
	void showPerson2(){
		cout << "Person2 show" << endl;
	}
};


void test() {
	//调用方式1
	Person1 person1;//实例化对象
	person1.showPerson1(); //调用类中的方法
	//调用方法2
	Person2* person2 = new Person2;
	person2->showPerson2();
}

int main() {
	test();
	system("pause");
	return 0;
}

补充:
在这里插入图片描述

类模板中的成员函数并不是一开始就创建的,在调用时才去创建

#include <iostream>
using namespace std;

class Person1{
public:
	void showPerson1(){
		cout << "Person1 show" << endl;
	}
};

class Person2{
public:
	void showPerson2(){
		cout << "Person2 show" << endl;
	}
};

template<class T>
class MyClass{
public:
	T obj;

	//类模板中的成员函数,并不是一开始就创建的,而是在模板调用时再生成

	void fun1() {
		obj.showPerson1(); 
	}
	void fun2() {
		obj.showPerson2(); 
	}

};

void test(){
	MyClass<Person1> m;
	m.fun1();
	//m.fun2();//编译会出错,说明函数调用才会去创建成员函数
}

int main() {
	test();
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值