在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; }