假设您要使用一个array对象来存储一年四个季度的开支:
std::array<double,4> expenses;
前面说过,要使用array类,需要包含头文件array,而名称array位于名称空间std中。
如果函数来显示expenses的内容,可按值传递expenses:
show(expenses);
但如果函数要修改对象expenses,则需将该对象的地址传递给函数(或传递引用)
fill(&expenses);
如何声明这两个函数呢?expenses的类型为array<double,4>,因此必须在函数原型中指定这种类型:
void show(std::array<double,4>da); //da an object
void fill (std::array<double,4>*pa); //pa a pointer to an object
请注意,模板array并非只能存储基本数据类型,它还可存储类对象。
程序清单7.15列出了该程序的完整代码。
//arrobj.cpp -- functions with array objects (C++11)
#include<iostream>
#include<array>
#include<string>
//constant data
const int Seasons = 4;
const std::array<std::string, Seasons>Snames =
{ "Spring","Summer","Fall","Winter" };
//function to modify array object
void fill(std::array<double, Seasons>* pa);
//function that uses array object without modifying it
void show(std::array<double, Seasons>da);
int main() {
std::array<double, Seasons>expenses;
fill(&expenses);
show(expenses);
return 0;
}
void fill(std::array <double, Seasons>* pa) {
using namespace std;
for (int i = 0; i < Seasons; i++) {
cout << "Enter " << Snames[i] << " expenses: ";
cin >> (*pa)[i];
}
}
void show(std::array<double, Seasons>da) {
using namespace std;
double total = 0.0;
cout << "nEXPENSESn";
for (int i = 0; i < Seasons; i++) {
cout << Snames[i] << ": $" << da[i] << endl;
total += da[i];
}cout << "Total Expenses: $" << total << endl;
}
程序说明
函数fill()和show()都有缺点。函数show()存在的问题是,expenses存储了四个double值,而创建一个新对象并将expenses的值复制到其中的效率太低。如果修改该程序时期处理每月甚至每日的开支,这种问题将更严重。
函数fill()使用指针来直接处理原始对象,这避免了效率低下的问题,但代码是看起来更复杂:
fill(&expenses); //don’t forget the &
…
cin>> (pa) [i];
在最后一条语句中,pa是一个指向array<double,4>对象的指针,因此pa为这种对象,而(*pa)[i]是该对象的一个元素。由于运算符优先级的影响,其中的括号必不可少。
后面会改进该代码。
最后
以上就是懵懂花生最近收集整理的关于7.8 函数与array对象(基础篇引入)的全部内容,更多相关7.8内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复