2017C++基础——网课笔记(15到18)

十五. 课程回顾和作业

1. 命名空间的作用。

相当于去限定作用域范围

namespace AAA{

        int a;

}

using AAA::a;

AAA::a;

using namespace AAA;

2. c语言的三目运算符,不可以当作左值。这是因为C语言中,三目运算符的结果是个子拷贝。

而C++的三目运算符的本质,是当作引用


3. const int a;在C++编译器中需要被初始化。因为这是常量。

4. 引用的特点:
(1)引用必须要初始化

(2)引用的本质是一个常量指针

(3)引用能够一定程度取代指针

5. 以下写法是否正确, int & a =40; 如果不正确,如何修改?

答:可以改为 const int &a =40; 这里意味着对一个常量的临时空间开辟引用 


十六. 昨日回顾(略)

十七. 内联函数

#include <iostream>
#include <ctime>

using namespace std;


void printAB(int a, int b)
{
    cout<<"a = "<<a <<"b = "<<b<<endl;
}

//注意的一点是inline必须是放在函数定义,而不是放在函数声明的位置,才可能生效
//另外,内联函数往往针对,逻辑简单,但是高频使用的函数。
inline void printAB_1(int a, int b)
{
    cout<<"a = "<<a <<"b = "<<b<<endl;
}

int main()
{
    int a = 10;
    int b = 20;

    double start = clock();
    for(int i = 0; i<10000; i++)
    {
        a++;
        b++;
        printAB(a,b);
    }
    double ending = clock();

    int c = 10;
    int d = 20;

    cout<<"-----------------------"<<endl;
    double start_1 = clock();
    for(int i = 0; i<10000; i++)
    {
        c++;
        d++;
        printAB(c,d);
    }
    double ending_1 = clock();
    cout<<"The during of printAB is:"<<ending-start<<endl;
    cout<<"The during of printAB_1 is:"<<ending_1-start_1<<endl;


    return 0;
}

/*
运行结果:
The during of printAB is:5712
The during of printAB_1 is:3295

显然内联函数更快,因为它被放在内存里,使用时省略了压栈和出栈的过程
*/

十八. 函数的默认参数和占位参数

#include <iostream>

using namespace std;

//默认参数
void func(int a = 666)
{
    cout<<"a = "<<a<<endl;
}

//占位参数
//占位参数的没有什么实在意义,只是为了设计语言的时候留待后续使用
//事实上,只有在操作符重载中,有作为”亚元“的作用
void func2(int x, int)
{
    cout<<"x = "<<x<<endl;
}

int main()
{
    int b = 1;
    func();
    func(b);

    func2(99,10);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/garrulousabyss/article/details/80646632