1,函数与指针
#include<iostream>
using namespace std;
int Sum (int *pa,int nLen);
void main()
{
int arr[]={1,2,3,4,5,6,7,8,9,010};
cout<<Sum(arr,10)<<endl;
}
int Sum(int *pa,int nLen)
{
int nRet=0;
for(int i=0;i<nLen;i++)
{
nRen+=pa[i];
}
return nRent;
}
在指针函数中的不到局部变量的值,只能得到地址,因为不能指向局部变量。
int *a();
int * b();
int i;
void main()
{
int *c=a();
cout<<*c<endl;//10
int *d=b();
cout<<*d<<endl;//7673859地址
}
int *a(){
{int i=10;
return i;
}
int *b(){
{
int j=20;
return j;
}
3,利用函数指针调用函数
#include<iostream>
using namespace std;
int Sum(int *pArr,int nLen);
void DispMsp(char *pMsg);
int (*fp1)(int *pArr,int nLen);
void (*fp2)(char *pMsg);
float (*fp3)(int *pArr,int nLen);
void main(){
fp1=Sum;
fp2=DispMsg;
int arr[]={1,2,3,4,5,6,7,8,9,10}
fp2("wwwwwwwwwwww");
(*fp2)("ddddddddddddd");
int nRet=fp1(arr,10);
cout<<nRet<<endl;
int Sum (int *pArr,int nLen){
int nRet=0;
for(int i=0;i<nLen;i++)
{
nRet+=pArr[i];
}
return nRent;
}
void Dispmsg(char*pMsg)
{
cout<<pMsg<<endl;
}
4,函数的缺省参数
#includ<iostream>
using namespace std;
void main()
{int i;
int nSum=0;
for(i=1;i<=num;;i++)
{
nSum+=i;
}
cout<<nSum<<endl;
}
void main()
{sum(100);
sum();
}
5,函数重载
int a(int b)
{
return a;
}
float a(float b)
{return b}
void main(){
int a=10;
float b=10.123;
cout<<a(a)<<endl;
cout<<b(b)<<endl;
}
6嵌套调用
fun1(int a,int b){
float v;
v=fun2(b-1,b+1);
}
fun2(int a,int b){
{}
递归调用
long fact(long n){
if(n==1)
return 1;
return fact(n-1)*n;
}
1,结构的定义
struct 结构名
{数据类型 成员名1;
数据类型 成员名2;
数据类型 成员名3;
。。。。}
1.2使用结构
#includes<iostream>
#include <string>
using namespace std;
struct Student
{
int nID;
char szName[20];
char szAddr[100];
char szPhone[15];
float fScore;
};
void main()
{
Student s;
s.nId=1;
strcpy(s.szName,"www");
strcpy(s.szAddr,"qqq");
strcpy(s.szPhone"3434");
s.fScore=93.5;
cout<<s.nID<<endl;
cout<<s.sxzName<<endl;
cout<<s.szAddr<<endl;
cout<<s.szPhone<<endl;
cout<<s.fSore<<endl;
}
1.3结构与指针
#includes<iostream>
#include <string>
using namespace std;
struct Student
{
int nID;
char szName[20];
char szAddr[100];
char szPhone[15];
float fScore;
};
void main()
{
Student s;
Student *ps;
ps=&s;
ps->nID=1;
strcpy(ps->szName,"liming");
>>>>>>
cout<<ps->nId<<endl;
。。。。。
}
1.4结构和数组
#includes<iostream>
#include <string>
using namespace std;
struct Student
{
int nID;
char szName[20];
char szAddr[100];
char szPhone[15];
float fScore;
};
void main()
{Student S[5]={{1,"lingmi",1988,"rrtew","4646",98.3},
{.............}........
}
cout<<s[i].nID<<endl;
........}
1.5结构和函数
2,枚举
#include<iostream>
#include<string>
using namespace std;
enum WEEKDAY{SUN=0,MON,TUE,WED,THU,FRI,SAT};
void PrintInfo(WEEKDAY Day);
void main()
[
WEEKDAY DAY=MON;
PrintInfo(day);
}
void PrintInfo(KEEKDAY DAY)
{
switch(day)
{case MON:
cout<<"今天是星期一"<<endl;
braek;
case .........
........}
3.用typedef声明类型
typedef struct tagStudent
{
int nID;
...........
..............
}