C++ Primer 学习笔记——函数(一)

来源:互联网 发布:python 爬虫 百科 编辑:程序博客网 时间:2024/06/05 00:34

函数三要素:返回类型,函数名,形参类型
在头文件中声明函数,在源文件中定义

局部静态对象
局部静态对象的生命周期贯穿函数调用及之后的时间

#include<iostream>using std::cout;int count_calls(){    static int ctr = 0;    return ++ctr;}int main(){    for (int i = 0; i != 10; i++)    {        cout << count_calls() << " ";    }    return 0;}

分离式编译

//Header.h#ifndef _SOURCE_H_#define _SOURCE_H_int count_calls();#endif//Source.cpp#include"Header.h"int count_calls(){    static int ctr = 0;    return ++ctr;}//main.cpp#include<iostream>#include"Header.h"using std::cout;int main(){    for (int i = 0; i != 10; i++)    {        cout << count_calls() << " ";    }    return 0;}

传值与传址
传值:
函数对形参做的所有操作不会影响实参
指针形参:
指针本身作为参数不会改变,改变的是指针指向的值

//6.10#include<iostream>using std::cout;void f(int *a, int *b){    int temp;    temp = *a;    *a = *b;    *b = temp;}int main(){    int x = 10, y = 20;    cout << x << y;    f(&x, &y);    cout << x << y;    return 0;}

传引用参数

void reset(int &i){i=0;}//改变了i所引用对象的值int j=42;reset(j);cout<<j;//此时J也被改变了

要避免直接拷贝,而考虑引用

//6.12#include<iostream>using std::cout;void f(int &a, int &b){    int temp;    temp = a;    a = b;    b = temp;}int main(){    int x = 10, y = 20;    cout << x << y;    f(x, y);    cout << x << y;    return 0;}
//6.15#include<iostream>#include<string>using std::cout;using std::string;string::size_type find_char(const string &s, char c, string::size_type &occurs)//string::size_type find_char(const string &s, char &c, string::size_type &occurs)//Error 1   error C2664: 'unsigned int find_char(const std::string &,char &,unsigned int &)' : cannot convert argument 2 from 'char' to 'char &'    实参是char类型而形参是char& 不能转变实参类型。//string::size_type find_char( string &s, char c, string::size_type &occurs)//s类型当为常量引用时,说明函数中不能改变s的值,而occurs在函数需要被改变,不能使用常量引用//并且使用常量引用,也可以通过字面值初始化,即find_char("hello",'o',num){    occurs = 0;    auto ret = s.size();    for (int i = 0; i != s.size(); ++i)    {        if (s[i] == c)        {            ret = i;//ret记录出现C的最后一次位置            ++occurs;        }    }    return ret;}int main(){    string s1 = "helloworld";    string::size_type count;    cout << find_char(s1, 'o', count);    cout << " " << count;    return 0;}

const实参和形参

void fcn(const int i)//fcn既可以传入int 也可以传入const int ,但不能再函数体内改变i//此时const为顶层const,被自动忽略,与void fcn(int i)相同

const int 不能用于初始化int
但是int 可以初始化const int

所以尽量使用常量引用:
1:函数里也不可以修改它的实参的值
2:实参的类型可以更多,不限制是否是const类型。普通引用是不接受常量实参而只接受非常量

//6.17#include<iostream>#include<string>using std::string;using std::cout;bool judge_capital(const string &s){    for (string::size_type i = 0; i != s.size(); ++i)    {        if (!islower(s[i]))            return true;    }    return false;}void change_string(string &s)//需要在函数体内改变s{    for (auto &i : s)//i如果不是引用,无法改变string 对象s的值,而只是改变一个s副本的值    {        i = toupper(i);    }}int main(){    string s1 = "Hello";    cout << judge_capital(s1);    change_string(s1);    cout << s1;    return 0;}
0 0
原创粉丝点击