C++ primer plus (第六版)第七章arrobj.cpp代码及解释

如有失误之处,还恳请指教!!!

//arrobj.cpp -- functions with array objects
#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
using namespace std;
//使用array对象来存储四个季度,表示这个数组含有4个string类型的元素,数组名称为Sname
const array<string, Seasons> Snames =
    {"Spring", "Summer", "Fall", "Winter"};
//函数原型:没有返回值,参数为array对象的指针
void fill(array<double, Seasons> *pa);
//函数原型:没有返回值,参数为array对象的值
void show(array<double, Seasons> da);
int main()
{
    //定义了一个array对象的数组,该数组含有4个double类型的元素
    //该数组名称为expences
    array<double, 4> expenses;
    //调用函数,并将数组expences的地址传递给该被调函数
    //按地址传递
    fill(&expenses);
    //调用函数,并将数组expenses作为参数传递给该函数
    //按值传递
    show(expenses);
    // std::cin.get();
    // std::cin.get();
    return 0;
}

void fill(array<double, Seasons> *pa)
{
    for (int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << Snames[i] << " expenses: ";
        //在上面的代码中将&expenses作为参数传递给pa,因此*pa相当于expenses
        //cin >> (*pa)[i] 相当于 cin >> expences[i];
        cin >> (*pa)[i];
    }
}

void show(array<double, Seasons> da)
{
    double total = 0.0;
    cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        cout << Snames[i] << ": $" << da[i] << '\n';
        total += da[i];
    }
    cout << "Total: $" << total << '\n';
}

猜你喜欢

转载自blog.csdn.net/weixin_38401090/article/details/86562430
今日推荐