C++的函数模板

本文通过示例介绍了C++中的函数模板使用方法,包括泛型最大值函数的实现,以及自定义类的声明与实例化过程。通过具体代码展示了如何在不同数据类型间复用相同的函数逻辑,并演示了如何定义和使用一个简单的学生信息类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码,下面是写的关于C++的一个很经典的函数模板方面的问题
#include<iostream>
using namespace std;

template <class T>

T max(T a, T b, T c)
{
	if (b > a)
		a = b;
	if (c > a)
		a = c;
	return a;
}
int main()
{
	int i1 = 185, i2 = 76, i3 = 567;
	double d1 = 56.84, d2 = 57.21, d3 = 45.33;
	long g1 = 67854, g2 = -912564, g3 = 673456;

	cout << "i_max = " << max(i1, i2, i3) << endl;
	cout << "i_max = " << max(d1, d2, d3) << endl;
	cout << "i_max = " << max(g1, g2, g3) << endl;
	getchar();
	getchar();
	return 0;
}
#include<iostream>
#include<cstring>
using namespace std;

class Student
{
private:
	int num;
	char name[20];
	char sex;
public:
	void set_data(int n, char *p, char a);
	void display();

};

void Student::set_data(int n, char *p, char a)
{
	num = n;
	strcpy_s(name, strlen(p) + 1,p);
	sex = a;
}

void Student::display()
{
	cout << "num:" << num << endl;
	cout << "name:" << name << endl;
	cout << "sex:" << sex << endl;
}
int main()
{
	Student stud1, stud2;
	stud1.set_data(1, "he", 'f');
	stud2.set_data(2, "she", 'm');
	stud1.display();
	stud2.display();
	system("pause");



	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值