C++ Primer Plus巩固 新特性 新理解(2)

来源:互联网 发布:xampp mac打开mysql 编辑:程序博客网 时间:2024/05/06 12:45

////  main.cpp//  C_Primer_Plus_2////  Created by Ben_22 on 14-5-10.//  Copyright (c) 2014年 Ben_22. All rights reserved.//#include <iostream>#include <string>int sum( const int arr[], size_t n);//三者等价const double *f1(constdouble ar[], int );const double *f2(constdouble [], int );const double *f3(constdouble *, int );int main(int argc, const char * argv[]){    using namespacestd;    // insert code here...    //判断单个字符的大小写数字空格等    //cctype库            /*     arr[2] = *(arr+2);     &arr[2] = arr + 2;     */        const int arr[6]{1,2,3,4,5,6};    cout<<sum(arr,6)<<endl;            //const深入理解    const int **p;    int *p1 ;    //*p = &p1; // *p对应的值是不可变的,但是P1的地址可以修改,所以not allowed    /*const最佳实践     尽量使用const     1:避免无意间修改数据     2:使用const使得函数能够处理const和非const实参。    */    int age = 29;    int bakage = 30;    const int *page = &age;    cout<<"const:"<<*page<<endl;    age = 44;    cout<<"const:"<<*page<<endl;    //*page = &bakage; not allowed            //指向函数的指针////    const double *f1(const double ar[], int );//    const double *f2(const double [], int );//    const double *f3(const double *, int );// 使用auto可以自动定义    const double *(* pf1)(constdouble *, int ) = f1;    auto p2 = f2;            //incline 内联函数。跟define有点类似,声明为incline的函数会被全部替换为函数体,代码执行的时候不会使用函数指针寻址,而是直接操作函数。        //什么时候会生成临时变量    //1.实参的类型正确,但不是左值    //2.实参的类型不正确,但可以转换成对应的格式。    long a=3,b=5;    swap(a, b);//正常情况下a b会long转换成int,会生成临时变量来进行变量值交换。但是结果却是正确的,因为C++默认禁止创建临时变量,所以结果正确。    cout<<a<<" "<<b<<endl;        //尽可能使用const的好处3    //使用const能够使函数正确的生成并使用临时变量    double && abc = a + b;    cout << abc<<endl;            return 0;}void swap(int &a, int &b){    int temp = a;    a = b;    b = temp;    return;}int sum(const int *arr, size_t n){    int sum = 0;    for (int i=0; i<n; i++) {        sum += arr[i];    }    return sum;}const double *f1(constdouble ar[], int ){    return ar;}const double *f2(constdouble ar[], int ){    return ar;}const double *f3(constdouble *ar, int ){    return ar;}


0 0