[C++ Primer Plus] 第9章、内存模型和名称空间——(一)程序清单

程序清单9.11-13(名称空间示例)

namesp.h  头文件:常量、结构定义、函数原型

 1 //namesp.h
 2 #include<string>
 3 //creat the pers and debts namespace
 4 namespace pers
 5 {
 6     struct Person
 7     {
 8         std::string fname;
 9         std::string lname;
10     };
11     void getPerson(Person &);
12     void showPerson(const Person &);
13 }
14 
15 namespace debts
16 {
17     using namespace pers;
18     struct Debt
19     {
20         Person name;              //name是Person的结构变量
21         double amount;
22     };
23     void getDebt(Debt &);
24     void showDebt(const Debt &);
25     double sumDebts(const Debt ar[], int n);
26 }

namesp.cpp  源代码文件:头文件中的函数原型对应的定义

 1 //namesp.cpp---namespaces
 2 #include <iostream>
 3 #include"namesp.h"
 4 
 5 namespace pers
 6 {
 7     using std::cout;
 8     using std::cin;
 9     void getPerson(Person &rp)
10     {
11         cout << "Enter first name: ";
12         cin >> rp.fname;
13         cout << "Enter last name: ";
14         cin >> rp.lname;
15     }
16     void showPerson(const Person &rp)
17     {
18         std::cout << rp.lname << ", " << rp.fname;
19     }
20 }
21 
22 namespace debts
23 {
24     void getDebt(Debt &rd)
25     {
26         getPerson(rd.name);
27         std::cout << "Enter debt: ";
28         std::cin >> rd.amount;
29     }
30     void showDebt(const Debt &rd)
31     {
32         showPerson(rd.name);
33         std::cout << ": $ " << rd.amount << std::endl;
34     }
35     double sumDebts(const Debt ar[], int n)
36     {
37         double total = 0;
38         for (int i = 0; i < n; i++)
39         {
40             total += ar[i].amount;
41         }
42         return total;
43     }
44 }

namespp.cpp  源代码文件(主函数):main()和其他函数原型及定义

 1 //using namespaces
 2 #include<iostream>
 3 #include"namesp.h"
 4 void other(void);
 5 void another(void);
 6 
 7 int main(void)
 8 {
 9     using debts::Debt;
10     using debts::showDebt;
11     Debt golf = { {"Benny","Goatsniff"},120.0 };
12     showDebt(golf);
13     other();
14     another();
15     system("pause");
16     return 0;
17 }
18 
19 void other(void)
20 {
21     using std::cout;
22     using std::endl;
23     using namespace debts;
24     Person dg = { "Doo","Glis" };
25     showPerson(dg);
26     cout << endl;
27     Debt zippy[3];
28     int i;
29     for (i = 0; i < 3; i++)
30         getDebt(zippy[i]);
31     for (i = 0; i < 3; i++)
32         showDebt(zippy[i]);
33     cout << "Total debt: $ " << sumDebts(zippy, 3) << endl;
34     return;
35 }
36 
37 void another() 
38 {
39     using pers::Person;
40     Person collector = { "Milo","Rightshift" };
41     pers::showPerson(collector);
42     std::cout << std::endl;
43 }

猜你喜欢

转载自www.cnblogs.com/Fionaaa/p/12686485.html
今日推荐