码迷,mamicode.com
首页 > 其他好文 > 详细

函数的使用

时间:2017-05-07 11:38:28      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:应该   cto   iostream   blog   main   迭代   使用   cpp   name   

在<<c++ primer>> 第四版中关于函数,我总结起来,主要分为这几个重点:参数传递,函数重载,函数指针。

一:参数传递

1 非引用形参:参数是以副本的形式接收。

指针形参

不能修改实参变量的值,但是可以通过形参的指针来修改该指针所指向的值。如果形参的定义是const,则可以接收非const和const变量,如果形参定义是非const,则只能接收非const变量。

技术分享
 1 #include "stdafx.h"
 2 #include <string>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 void prt(int *str)
 8 {
 9     cout << *str << endl;
10 }
11 int main()
12 {
13     const int value = 123;
14     const int *str = &value;
15     prt(str);
16     prt(const_cast<int*>(str));
17     system("pause");
18     return 0;
19 }
View Code

 

prt(str) 这里报错,因为传入的是const型的指针,但是函数接收的是非const类型,所以这里需要去掉const属性,使用了const_cast<int*>(str)转换。

 

const 形参

因为参数是以副本形式传递,因此const 形参既可以接收普通的变量,也可以接收const形式的实参。

技术分享
 1 #include "stdafx.h"
 2 #include <string>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 void prt(const string str)
 8 {
 9     cout << str << endl;
10 }
11 int main()
12 {
13     string str("helloworld");
14     const string str2("!!!");
15     prt(str);
16     prt(str2);
17     prt("we did it");
18     system("pause");
19     return 0;
20 }
View Code

 

 

2 引用形参:参数以引用的形式接收,因此在函数内可以修改实参的值。主要用途如下:

修改实参值

可以通过引用形参返回额外的信息

避免复制(一般大对象或者是参数对象没法复制时)

 

3 vector对象和数组对象

vector形参

如果参数是普通非引用类型的vector对象,则参数传递会复制vector中每个对象。一般通过传递迭代器来进行传递vector对象。

 

数组形参

不能复制数组以及数组会自动转换成指向第一个元素的指针。

传递方式有两种:传递迭代器或者是显式传入数组大小。

如果以非引用方式传递数组,则数组大小会被忽略掉,如果以引用方式传递数组,则会带上数组大小,那么只能传递函数声明中指定大小的数组。----不建议使用。

 

 

二 函数重载

每一个版本的重载函数都应该在同一个作用域中定义。

确定重载函数的步骤:

1 候选函数:和被调用函数同名的函数。

2 可行函数:函数的参数类型以及个数匹配的函数。

3 最佳匹配:实参类型和形参类型越接近则越匹配。

在重载函数的调用过程当中,是按照以上三个过程来寻找被调用的函数。

 

三 函数指针

函数指针可以用来调用函数以及可以作为函数的参数进行传递。看如下例子:

技术分享
 1 // FunctionTest.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <string>
 6 #include <iostream>
 7 
 8 using namespace std;
 9 
10 typedef int(*PF)(const string str1, const string str2);
11 
12 int prt1(string str1,string str2,int(*func)(string, string))
13 {
14     func(str1,str2);
15     return 1;
16 }
17 
18 int prt(string str1, string str2)
19 {
20     cout << str1 << "-->" << str2 << endl;
21     return 1;
22 }
23 
24 int main()
25 {
26     PF pf = prt;
27     pf("hello","world");
28     prt1("hello","world",prt);
29     system("pause");
30     return 0;
31 }
View Code

 

使用了typedef定义了一个函数指针,该函数指针指向了一个具有两个形参为string,返回值为int的函数。

typedef int(*PF)(const string str1, const string str2);

 

这里又定义了一个prt函数,这个函数刚好有两个string 型的形参,返回值为int。所以可以使用PF指向该prt函数。

prt1函数是传递了两个string字符串,同时传递了一个函数指针。在prt1内部,直接通过形参上的func来进行调用即可。

 

函数的使用

标签:应该   cto   iostream   blog   main   迭代   使用   cpp   name   

原文地址:http://www.cnblogs.com/lucy-lizhi/p/6819721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!