代码改变世界

c++ primer学习笔记(6)-函数(2)

2011-02-24 20:44  Clingingboy  阅读(300)  评论(0编辑  收藏  举报

 

一.默认实参

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.不要返回函数局部对象引用

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