C++自定义函数

函数原型和定义

在写程序的过程中,函数是必不可少的。创建自己的函数就必须为函数提供定义、提供函数原型和调用函数。下面这段代码演示了这段过程。

#include<iostream>
void simple();//函数原型
int main()
{
	using namespace std;
	cout << "main函数调将要用simple函数。" << endl;
	simple();//函数调用
	cout << "main函数完成了simple函数的调用。" << endl;
	return 0;
}

void simple()//函数定义
{
	using std::cout;
	cout << "我是 simple函数。\n";
}

 

函数参数和返回值

一个自定义函数可以有一个参数、多个参数或者没有参数,而函数的返回值只能有一个或者没有,没有的用void定义,C++对函数的返回值有一定的限制:不能是数组,但可以是其他任何类型——整数、浮点数、指针,甚至可以是结构和对象!(虽然C++不能直接返回数组,但可以将数组作为结构或对象组成部分来返回。)

#include<iostream>
using namespace std;
void function1();//定义没有返回值,没有参数的函数
int add(int x, int y, int z);//定义返回a,b,c和的函数
int main()
{
	int a = 10, b = 20, c = 30;
	function1();
	cout << "a+b+c=";
	cout << add(a, b, c) << endl;
	return 0;
}
void function1()
{
	cout << "我是没有返回值,没有参数的函数。\n";
}

int add(int x, int y, int z)
{
	return x + y + z;
}

 

函数add将a的值传递给了x,将b的值传递个了y,将c的值传递给了z,这种传递是按值传递的,在C++自定义函数中,还有两种传递方式,按指针传递和引用传递。下面是这三中方式的比较。

#include<iostream>
using namespace std;
//在这里定义一个swap函数,传入两个数值,并交换他们的数值
void swap1(int x, int y);//数值传递
void swap2(int* x, int* y);//指针传递
void swap3(int& x, int& y);//引用传递
int main()
{
	int a = 10, b = 20;
	cout <<"调用函数前的值"<< "a= "<<a <<"\t"<<"b= "<<b << endl;
	swap1(a, b);//调用swap1函数
	cout << "调用swap1函数:" << "a= " << a << "\t" << "b= " << b << endl << endl;

	cout << "调用函数前的值" << "a= " << a << "\t" << "b= " << b << endl;
	swap2(&a, &b);//调用swap2函数
	cout << "调用swap2函数:" << "a= " << a << "\t" << "b= " << b << endl << endl;

	cout << "调用函数前的值" << "a= " << a << "\t" << "b= " << b << endl;
	swap3(a, b);//调用swap2函数
	cout << "调用swap3函数:" << "a= " << a << "\t" << "b= " << b << endl;
	return 0;
}
void swap1(int x, int y)
{
	int temp = x;//将x的值付给临时变量
	x = y;
	y = temp;
}

void swap2(int* x, int* y)
{
	int temp = *x;//将x的值付给临时变量
	*x = *y;
	*y = temp;
}

void swap3(int& x, int& y)
{
	int temp = x;//将x的值付给临时变量
	x = y;
	y = temp;
}

程序的运行结果

 调用swap1时,x得到的是a值得拷贝,y得到的是b值得拷贝,所以改变x和y的值并不影响a和b的值,所以调用swap1后a和b的值后都保持不变,而调用swap2和swap3时,x和y 得到的是a和b的地址,所以改变x和y的值时,a和b的值也随之被改变。这就是按值传递和按指针传递的本质区别。

按值传递需要对传递的值进行拷贝,这样会对计算机进行一定的消耗,而按指针传递只是传递数据的地址,这样大大提高了函数调用时的性能。当传递的值比较大时,可以用指针传递从而减少计算机的开销。

函数和数组

#include<iostream>
using namespace std;
int sum(int arr[], int n);
//int sum(int* arr, int n);
int main()
{
	int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
	cout << sum(a, 10);
	return 0;
}

int sum(int arr[], int n)
{
	int sum = 0;
	for (int i = 0; i < n; i++)
		sum += arr[i];
	return sum;
}

谢谢大家!

猜你喜欢

转载自blog.csdn.net/xiao_qiai/article/details/83241311