【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++学习笔记:void*变量,在函数内必须要明确变量类型
- C++学习笔记之函数如何返回字符串(char型)
- Effective c++学习笔记——条款6,不想自动生成函数,要明确拒绝
- C++学习笔记:函数模版
- 2012/1/19 《C++ Primer Plus》第七章:函数——C++编程模块 学习笔记
- C++学习笔记1———getline()函数
- 2012/1/21 《C++ Primer Plus》第八章:函数探幽 学习笔记
- C++学习笔记(3)——成员变量、成员函数的指针
- C++学习笔记-6-函数
- 2012/1/21 《C++ Primer Plus》第八章:函数探幽 学习笔记
- c++学习笔记--虚函数和多态的重新认识
- Inside the C++ Object Model 学习笔记 第四章 函数语意学
- C++中虚函数学习笔记
- C++学习笔记-8-函数执行的顺序
- C++学习笔记(12)——多态与虚函数
- C++ 函数模板和排序的函数模板——学习笔记
- C++学习笔记5---虚函数的工作原理
- C/C++中关于地址、指针和引用变量的学习笔记(四) : 函数
- 2012/1/19 《C++ Primer Plus》第七章:函数——C++编程模块 学习笔记
- C++pirmer 学习笔记之函数定义