C++Primer Plus-第七章 C++编程模块学习

1. 当且仅当用于函数头或函数原型中时,int* array和int array[]含义才是相同的。都意味着array是一个int型指针。一般当指针指向数组的第一个元素时,用数组表示法,而指向一个独立值时,用指针表示法。

2. array[i] = *(array + i):表示数组第i个元素的值

   &array[i] = array + i:表示数组第i个元素的地址。

3. 数组作为参数:实际并没有传递数组的内容,而是将数组的地址,元素种类,元素个数传递给函数。(常规变量传递的是copy,数组时,由于是地址,所以是原来的数组而不是copy)

4. 根据数据的存储方式和使用方式来定义数据的类型。

5. 指向常量的指针:const int* pt = &a;  *pt为const,即无法使用指针修改*pt的值;但是pt可以其他地址;

区分指针本身是常量:int* const pt = &a; * const pt为常量指针,所以pt不能指向其他地址,但是*pt可以修改。

    

6. C++禁止cost地址赋给非const指针。

7. 函数定义时,参数尽量使用const:避免数据被无意间修改引发bug;const可以接收const和非const参数。如果不加const只能接收非const参数。

 ​​​​​​​

 

 1 /*
  2  * auther: tianqiang
  3  * date:2022/06/26
  4  * decription: 数组作为函数参数传递
  5  *             实际传入的是数组的首地址,和元素种类和元素个数
  6  *             计算数组大小:sizeof(数组名)/sizeof(元素类型)
  7  */
  8  #include<iostream>
  9 using namespace std;
 10
 11 int sumArray(const int array[], int size); //如果指向的是数组的第一个元素,则用这个形式更直观
 12 int sumPointer(const int* aPointer, int size); //如果指向的是一个独立的值,则使用这个形式更直观
 13 int sumArrayPointer(const int* begin, const int* end); //通过传递两个指针来指定数组区间:数组区间传递
 14
 15 int main()
 16 {
 17     int score[5] = {60, 90, 100, 98, 99};
 18     cout << "sizeof score = " << sizeof(score) << endl;
 19     int totalScore = sumArray(score, sizeof(score) / sizeof(int));
 20     cout << "totalScore = " << totalScore << endl;
 21
 22     int total = sumPointer(score, sizeof(score) / sizeof(int));
 23     cout << "total = " << total << endl;
 24
 25     int totalAP = sumArrayPointer(score, score + sizeof(score) / sizeof(int));
 26     cout << "totalAP =" << totalAP << endl;
 27 }
 28
 29 int sumArray(const int array[], int sizeofArray)
 30 {
 31     int total = 0;
 32     for (int i = 0; i < sizeofArray; i++)
 33     {
 34         total += array[i];
 35     }
 36     return total;
 37 }
 38
 39 int sumPointer(const int* aPointer, int size)
 40 {
 41     int total = 0;
 42     for(int i =0; i < size; i++)
 43     {
 44         total += aPointer[i];
 45     }
 46     return total;
 47 }
 48
 49 int sumArrayPointer(const int* begin, const int* end)
 50 {
 51     const int* pt;
 52     int total = 0;
 53     for(pt = begin; pt !=end; pt++)
 54     {
 55         total += *pt;
 56     }
 57     return total;
 58 }
 59

  函数无法返回字符串,但是可以返回字符串的地址。这样做更加高效。

结构体变量的行为更接近于基本变量:按值传递,可以互相赋值,取地址使用&。

如需要多个字符串,可以声明一个string对象数组,而不是char二维数组。

传递引用可以解决效率低和书写形式复杂的问题。

函数指针:函数名,函数在内存开始的地址。

一定要区分传递的是函数的地址还是函数的返回值。

typedef定义类型的别名更加灵活。

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值