C++命名空间使用代码

namesp.h

 1 #pragma once

 2 #include <string>

 3 

 4 namespace pers

 5 {

 6     using namespace std;

 7     struct Person

 8     {

 9         string fname;

10         string lname;

11     };

12     void getPerson(Person &);

13     void showPerson(const Person &);

14 }

15 

16 namespace debts

17 {

18     using namespace pers;

19     struct  Debt

20     {

21         Person name;

22         double amount;

23     };

24     void getDebt(Debt &);

25     void showDebt(const Debt &);

26     double sumDebts(const Debt ar[], int n);

27 }

namesp.cpp

 1 #include "namesp.h"

 2 #include <iostream>

 3 

 4 using namespace std;

 5 

 6 void pers::getPerson(Person & rp)

 7 {

 8     cout << "Enter first name: ";

 9     cin >> rp.fname;

10     cout << "Enter last name: ";

11     cin >> rp.lname;

12 }

13 

14 void pers::showPerson(const Person & rp)

15 {

16     cout << rp.fname << ", " << rp.lname;

17 }

18 

19 void debts::getDebt(Debt & rd)

20 {

21     getPerson(rd.name);

22     cout << "Enter debt: ";

23     cin >> rd.amount;

24 }

25 

26 void debts::showDebt(const Debt & rd)

27 {

28     showPerson(rd.name);

29     cout << ": $" << rd.amount << endl;

30 }

31 

32 double debts::sumDebts(const Debt ar[], int n)

33 {

34     double total = 0;

35     for (int i = 0; i < n; i++)

36     {

37         total += ar[i].amount;

38     }

39     return total;

40 }

namessp.cpp

 1 #include <iostream>

 2 #include "namesp.h"

 3 

 4 void other(void);

 5 void another(void);

 6 

 7 int main()

 8 {

 9     using debts::Debt;

10     using debts::showDebt;

11 

12     Debt golf = { {"Benny","Goatsniff"},120.0 };

13     showDebt(golf);

14     other();

15     another();

16     

17     std::cin.get();

18     return 0;

19 }

20 

21 void other(void)

22 {

23     using namespace std;

24     using namespace debts;

25 

26     Person dg = { "Doodles","Glister" };

27     showPerson(dg);

28     cout << endl;

29 

30     Debt zippy[3];

31     int i;

32     for (int i = 0; i < 3; i++)

33     {

34         getDebt(zippy[i]);

35     }

36     for (i = 0; i < 3; i++)

37     {

38         showDebt(zippy[i]);

39     }

40     cout << "Total debt: $" << sumDebts(zippy, 3) << endl;

41     return;

42 }

43 

44 void another(void)

45 {

46     using pers::Person;

47     Person collector = { "Milo","Rightshift" };

48     pers::showPerson(collector);

49     std::cout << std::endl;

50 }

 

你可能感兴趣的:(命名空间)