您的位置:首页 > 编程语言 > C语言/C++

【C++】学习笔记三十六——函数和array对象

2017-03-09 22:07 190 查看

函数与array对象

  在C++中,类对象是基于结构的,因此结构编程方面的有些考虑因素也适用于类。例如,可按值将对象传递给函数,此时函数处理的是原始对象的副本。也可传递指向对象的指针,这让函数能够操作原始对象。

  

  假设要使用一个array对象来存储一年四个季度的开支:

std::array<double, 4> expenses;


  如果函数用来显示expenses的内容,可按值传递expenses:

show(expenses);


但如果要修改对象expenses,则需将该对象的地址传递给函数:

fill(&expenses);


expenses的类型为array

void show(std::array<double, 4> da);
void fill(std::array<double, 4> * pa);


注意,模板array并非只能存储基本数据类型,它还可存储类对象。

程序7.15

#include<iostream>
#include<array>
#include<string>

using namespace std;
const int Seasons = 4;
const array<string, Seasons> Snames = { "Spring","Summer","Fall","Winter" };

void fill(array<double, Seasons> * pa);
void show(array<double, Seasons> da);

int main()
{
array<double, Seasons> expenses;
fill(&expenses);
show(expenses);
system("pause");
return 0;
}

void fill(array<double, Seasons> *pa)
{
for (int i = 0; i < Seasons; i++)
{
cout << "Enter " << Snames[i] << " expenses: ";
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] << endl;
total += da[i];
}
cout << "Total Expenses: $" << total << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++