2019.01.17(C++语言基础)
一.C++语言基础(一)
C++语言简介
二.C++语言基础(二)
1.动态内存
//例1.2从堆内存中获取一个整形数组,赋值后并打印出来。
#include<iostream>
using namespace std;
void main()
{
int n;
int *p;
cout<<"Please input the length of the array:";
cin>>n;
if((p=new int[n])==0)
{
cout<<"can't allocate more memory,terminating." <<endl;
exit(1);
}
for(int i=0;i<n;i++)
p[i]=2*i;
cout<<"Now output the array:" <<endl;
for(i=0;i<n;i++)
cout<<p[i]<<" ";
cout<<endl;
delete p;
}
2.引用
三.C++语言基础(三)
1.内联(inline)函数
内联函数的限制
1.不能有递归
2.不能包含静态数据
3.不能包含循环
4.不能包含switch和goto语句
5.不能包含数组
举例:
#include<iostream>
using namespace std;
inline float f(int x)
{
if(x%2!=0) return (1.0/x);
else return (-1.0/x);
}
void main()
{
int s=0,j;
for(j=1;j<=100;j++)
cout<<f(j)<<endl;
}
2.带默认参数的函数
3.函数重载
4.函数模板
举例:
#include <iostream>
using namespace std;
template <class T>
T max(T a[],int n)
{
int i;
T maxv=a[0];
for(i=1;i<n;i++)
if(maxv<a[i])
maxv=a[i];
return maxv;
}
void main()
{int a[]={1,5,3,7,4,9,-2,8};
float b[]={1.2,4.5,6.7,-2.4,7.5};
cout<<"maxa="<<max(a,8)<<endl;
cout<<"maxb="<<max(b,5)<<endl;
}
运行结果**********************************
maxa=9
maxb=7.5