《C++ Primer Plus》第7章学习笔记

2021-06-08  本文已影响0人  蓬篙人

内容思维导图

第7章 函数

1. 复习函数的基本知识

// 函数使用示例
#include <iostream>

void simple();    // 函数原型

int main()
{
    using namespace std;
    cout << "main() will call the simple() function: \n";
    simple();     // 函数调用

    return 0;
}
// 函数定义
void simple()
{
    using namespace std;
    cout << "I'm but a simple function.\n";
}
// void函数
void functionName(parameterList)
{
    statements
    return;        // 可选
}
// 有返回值函数
typeName functionName(parameterList)
{
    statements
    return value;    // 值将转换为类型typeName
}
void say(...);

2. 函数和数组

// 声明指向常量的指针
int age = 39;
const int* pt = &age;
*pt += 1;              // 错误!!!
int age2 = 80;
pt = &age2;           // 可以
// 声明指针常量
int sloth = 3;
int* const finger = &sloth;
// 指向const对象的const指针
double trouble = 2.0E30;
const double* const stick = &trouble;
const int** pp2;
int* p1;
pp2 = &p1;    // 不允许

3. 函数和二维数组

int data[3][4] = { { 1, 2, 3, 4 }, { 9, 8, 7, 6 }, { 2, 4, 6, 8 } };
int total = sum(data, 3);
// 上述函数sum()的原型如下:
int sum(int (*ar2)[4], int size);
// 或
int sum(int ar2[][4], int size);

4. 函数和C-风格字符串

5. 递归

void recurs(argumentlist)
{
    statements1
    if(test)
        recurs(arguments)
    statements2
}
// 分而治策略示例
void subdivide(char ar[], int low, int hight, int level)
{
    if(level == 0)
        return;
    int mid = (high + low) / 2;
    ar[mid] = '|';
    subdivide(ar, low, mid, level - 1);
    subdivide(ar, mid, high, level - 1);
}

6. 函数指针

double pam(int);     // 函数原型
double (*pf)(int);   // pf为带一个int参数返回值类型为double的函数的指针
double pam(int);    
double (*pf)(int);   
pf = pam;
double y1 = (*pf)(5);   // 使用指针调用pam()函数
double y2 = pf(5);      // 与上行代码等效
上一篇 下一篇

猜你喜欢

热点阅读