今天复习了类型定义和函数。 先所类型定义: 举个例子 typedef double wages,bonus; 以后可以用wages,bonus来定义周薪和月薪了 比如: wages weekly; bonus monthly; 其他的定义方法: 例如: typedef char * string; typedef string months[3]; months spring = {"February","March","April"}; 关于函数: 函数的有定义和说明的两件工作,如果定义在先,调用在后,调用前可以不用说明;如果定义在后,调用在先,就需要说明: 例如: #include<iostream.h> void fun1(); void main() { cout<<"This is fun1"<<endl; fun1(); } void fun1() { cout<<"fun1 is executed."<<endl; } 或者这样 #include<iostream.h> void fun1() { cout<<"fun1 is executed."<<endl; } void main() { cout<<"This is fun1"<<endl; fun1(); } 函数的传值调用,函数的传址调用,函数的引用调用 分别如下: void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } void swap(int *x, int* y) { int temp; temp=*x; *x=*y; *y=temp; } void swap(int &x, int &y) { int temp; temp=x; x=y; y=temp; } 如果调用方式为swap(a,b); 后两者交换a,b的值。第一种方式不交换。 关于设定函数的默认值: C++编译器给函数参数赋值顺序为从左向右,所以可以从最右边开始为参数设定默认值: 比如: int m=10; int add(int a, int b, int c, int d=10, int e=m) { return (a+b+c+d+e); } 调用z=add(1,2,3)时,输出就为26 注意:参数当中也可以用表达式进行赋值,比如本例使用了:int e=m 使用数组作为函数参数: 1. 实参形参都用数组: int a[8]={1,2,3,4,5,6,7}; void fun(int b[],int n){...}; fun(a,8); 数组a和数组b在内存当中共享一个存储区,所以a当中的内容和b当中是一致的,会根据函数fun发生变化。 2.形参和实参都用指针: int a[8]={1,2,3,4,5,6,7,8}; void fun(int *p,int n){...}; 可以如下调用 fun(a,8); 或者: int *q=8; fun(q,8); 3.实参用数组名,形参用引用 例: typedef int array[8]; int a[8]={1,2,3,4,5,6,7}; void fun(array &b,int n)// or void fun(int &b[8],int n);个人理解可以这样,书上是第一种 调用使用 fun(a,m); 另外像内联函数是用函数体替换代码,不是到指定位置调用函数,必须在调研之前实现以及像函数重载概念之类我在这里就不罗唆了。

评论