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

第八章:函数探幽

时间:2015-01-20 22:08:55      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

8.1题

 1 #include<iostream>
 2 void silly(const char * s,int n = 0);
 3 int main()
 4 {
 5     char *pointer = "lala";
 6     silly("hello?");
 7     for(int i = 0; i < 5; i++)
 8         silly(pointer,i);
 9 }
10 void silly(const char * s,int n)
11 {
12     static int use = 0;
13     int limit = ++use;
14     for(int i = 0; i < limit ; i++)
15         std::cout << s << \t << "limit = " << limit << \t <<"i = " << i << std::endl;
16 }

 stastic限制局部变量

8.4题

 1 #include <iostream>
 2 #include <cstring> // for strlen(), strcpy()
 3 using namespace std;
 4 struct stringy {
 5  char * str; // points to a string
 6  int ct; // length of string (not counting ‘\0‘)
 7  };
 8 void show(const char *str, int cnt = 1);
 9 void show(const stringy & bny, int cnt = 1);
10 void set(stringy & bny, const char * str);
11 int main(void)
12 {
13  stringy beany;
14  char testing[] = "Reality isn‘t what it used to be.";
15  set(beany, testing); // first argument is a reference,
16  // allocates space to hold copy of testing,
17  // sets str member of beany to point to the
18  // new block, copies testing to new block,
19  // and sets ct member of beany
20  show(beany); // prints member string once
21  show(beany, 2); // prints member string twice
22  testing[0] = D;
23  testing[1] = u;
24  show(testing); // prints testing string once
25 show(testing, 3); // prints testing string thrice
26  show("Done!");
27  return 0;
28 }
29 //对应show(testing) 
30 void show(const char *str, int cnt)
31 {
32     while(cnt-- > 0)
33         cout << str <<endl;
34 }
35 //对应show(beany) 
36 void show(const stringy &bny, int cnt)
37 {
38     while(cnt-- > 0)
39         cout << bny.str << endl;
40 }
41 void set(stringy & bny,const char *str)
42 {
43     bny.ct = strlen(str);
44     bny.str = new char[bny.ct + 1];
45     strcpy(bny.str,str);
46 }

函数原型中cnt = 1,如果默认不输入cnt ,那么就是默认的1;如果输入一个值n,得到的就是新值n。例如代码的20和21行。

8.5题

 

 1 #include<iostream>
 2 template <class T>
 3 T max5(T ar[])
 4 {
 5     int n;
 6     T max = ar[0];
 7     for(n = 0; n < 5; n++)
 8         if(ar[n] > max)
 9             max = ar[n];
10     return max;
11 }
12 const int LIMIT = 5;
13 int main()
14 {
15     double arr1[LIMIT] = {12,32.23,-423,-37.987,35.9};
16     int arr2[LIMIT] = {34,26,42,65,-14};
17     std::cout << max5(arr1) << std::endl;
18     std::cout << max5(arr2) << std::endl;
19 }
20  

 

函数模版。

 

第八章:函数探幽

标签:

原文地址:http://www.cnblogs.com/fudianheg/p/4235946.html

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