third class 函数

本文详细介绍了 C++ 中的缺省参数用法,并通过实例展示了如何使用模板来实现通用函数。同时,文章还讲解了动态内存分配及回收的方法。

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

//default.cpp
//default parameter:缺省(默认)参数
#inclide<iostream>
using namespace std;
int max(int a[],int n=2)//n=2 默认数组元素个数
{
	int t=a[0];
	for(int i=1;i<n;i++)
		t=(a[i]>t)?a[i]:t;
	return t;
}
//dynamically allocating memory 动态定义数组
//int main()
//{
//		int *a=NULL,n;
//		cout<<"How many students:";
//		cin>>n;
//		a = new int[n];
//	int *b=NULL;
//	b = new int(6);//分配的这个内存中存储的数为6
//			cout<<"Max = "
//		<<max(a,n)
//		<<endl;
delete b;//单个直接回收,delete回收
delete []a;//数组回收,
//		return 0;
//		
//}
int main()
{
	int a[]={5,4,2,10,3,6,8,9,0};
	cout<<"Max = "
		<<max(a,sizeof(a)/sizeof(int))
		<<endl;
	return 0;
}


//function template
template<class T>//函数模板
T max(T a,T b)
{
	return(a>b)?a:b; 
}

template<class T>
void swap(T&a, T&b)
{
	T t=a;
	a=b;
	b=t;
}

template<class T>
bool equal(T a,T b)
{
	return a == b;
}

template<>
bool equal(char*a,char*b)//specialization 特化
{
	return strcmp(a,b)==0;
}
int max(int a[],int n)
{
	int t=a[0];
	for(int i=1;i<n;i++)
		t=max(t,a[i]);//instantiation(模板实例化)
					 //int max(int,int){...}
}

template<class T, int C>
void ff(T x)
{
	T *a;
	a= new T[C];
	a[0] = x;

	return;
}


#include<iostream>
#include<string>
using std::count;
using std::string;
//using namespace std;
namespace MyNames2{
	double max(double a[],int n);return(-1);
};
namespace MyNames2{
	const int max = 10086;
};


using MyNames::max;

int main()
{
	double f[10]={0.0};
	cout<<"hello;world!"<<endl;
	cout<<max(f,10)<<endl;
	return 0;
}



for(int i=0;i<10;i++)
cin>>f[i];//


int x = 10;
int&rx = x;
rx++;
int* px = &x;
(*px)++;//x加了两次



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值