7.8 函數與array對象(基礎篇引入)

假設您要使用一個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 << "\nEXPENSES\n";
	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]是該對象的一個元素。由於運算符優先級的影響,其中的括號必不可少。

後面會改進該代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章