zoukankan      html  css  js  c++  java
  • c++ primer学习笔记(6)函数(2)

    一.默认实参

    string screenInit(string::size_type height = 24,
                        string::size_type width = 80,
                        char background = ' ' );
    

    要么全有,要么全没有.

    调用

             string screen;
    screen = screenInit();       // equivalent to screenInit (24,80,' ')
    screen = screenInit(66);     // equivalent to screenInit (66,80,' ')
    screen = screenInit(66, 256);       // screenInit(66,256,' ')
    screen = screenInit(66, 256, '#');
    

    二.函数静态局部变量

    这个变量定义于函数中,但生命周期却跨越了函数,对象一旦被创建,直至程序结束前才被撤销

    size_t count_calls()
    {
        static size_t ctr = 0; // value will persist across calls
        return ++ctr;
    }
    int main()
    {
        for (size_t i = 0; i != 10; ++i)
            cout << count_calls() << endl;
        return 0;
    }
    

    输出:

    image

    三.内联函数

    一个函数前面加上inline关键字,则成为内联函数.

    特性:将函数展开,消除函数调用的额外开销(提高性能),适用于调用次数多,代码精湛的

    四.返回值

    1.非引用返回

    int Max(int &a,int &b)
    {
        if(a>b)
            return a;
        return b;
    }
    

    Test

    int a=10;
    int b=20;
    int c=Max(a,b);
    int *d=&b;
    int *e=&c;
    bool f=d==e;
    cout << f << endl;
    

    输出0,地址不同

    2.返回引用

    int &Max2(int &a,int &b)
    {
        if(a>b)
            return a;
        return b;
    }
    

    唯一的变化就是返回值变了

    重新测试

    int a=10;
    int b=20;
    int &c=Max2(a,b);
    int *d=&b;
    int *e=&c;
    bool f=d==e;
    cout << f << endl;
    

    返回1,地址相同

    3.不要返回函数局部对象引用

    当函数执行完毕后,将要对布局对象进行释放

  • 相关阅读:
    python的多进程
    sqlalchemy的缓存和刷新
    uuid
    区块链的理解
    列表推导式,两个for循环的例子
    Fiddler 抓包工具总结
    python---webbrowser模块的使用,用非系统默认浏览器打开
    使用jmeter做web接口测试
    selenium2中关于Python的常用函数
    Selenium2+Python自动化学习笔记(第1天)
  • 原文地址:https://www.cnblogs.com/Clingingboy/p/1964143.html
Copyright © 2011-2022 走看看