【C++】名称空间示例:一个小型程序的完全实现,深入理解程序结构!!!
【摘要】 目录
这个程序包含三部分:
namesp.h
namesp.cpp
namessp.cpp
运行结果:
这个程序包含三部分:
namesp.h
namesp.cpp
namessp.cpp
namesp.h
//namesp.h #include<string>// 创造名称空间namespace pers{ struct Person { std...
目录
这个程序包含三部分:
namesp.h
namesp.cpp
namessp.cpp
namesp.h
-
//namesp.h
-
#include<string>
-
// 创造名称空间
-
namespace pers
-
{
-
struct Person
-
{
-
std::string fname;
-
std::string lname;
-
};
-
void getPerson(Person &);
-
void showPerson(const Person &);
-
}
-
-
namespace debts
-
{
-
using namespace pers;
-
struct Debt
-
{
-
Person name;
-
double amount;
-
};
-
void getDebt(Debt &);
-
void showDebt(const Debt &);
-
double sumDebts(const Debt ar[], int n);
-
-
}
namesp.cpp
-
// namesp.cpp -- namespaces
-
#include<iostream>
-
#include"namesp.h"
-
-
namespace pers
-
{
-
using std::cout;
-
using std::cin;
-
void getPerson(Person & rp)
-
{
-
cout << "Enter first name: ";
-
cin >> rp.fname;
-
cout << "Enter last name: ";
-
cin >> rp.lname;
-
}
-
void showPerson(const Person & rp)
-
{
-
std::cout << rp.lname << ", " << rp.fname;
-
}
-
}
-
-
//头文件中已经using namespace pers;,所以showPerson可以用了
-
namespace debts
-
{
-
void getDebt(Debt & rd)
-
{
-
getPerson(rd.name);
-
std::cout << "Enter debt: ";
-
std::cin >> rd.amount;
-
}
-
void showDebt(const Debt & rd)
-
{
-
showPerson(rd.name);
-
std::cout << ": $ " << rd.amount << std::endl;
-
}
-
double sumDebts(const Debt ar[], int n)
-
{
-
double total = 0;
-
for (int i = 0; i < n; i++)
-
{
-
total += ar[i].amount;
-
}
-
return total;
-
}
-
}
namessp.cpp
-
// namessp.cpp -- 使用名称空间
-
#include<iostream>
-
#include"namesp.h"
-
void other(void);
-
void another(void);
-
int main(void)
-
{
-
using debts::Debt;
-
-
using debts::showDebt;
-
Debt golf = { { "Benny", "Goastsinff" }, 120.0 };//忘了可以查看Debt定义
-
showDebt(golf);
-
other();
-
another();
-
return 0;
-
}
-
-
void other(void)
-
{
-
using std::cout;
-
using std::endl;
-
using namespace debts;
-
Person dg = { "Doodels", "Glister" };
-
showPerson(dg);
-
cout << endl;
-
Debt zippy[3];
-
int i;
-
for ( i = 0; i < 3; i++)
-
{
-
getDebt(zippy[i]);
-
}
-
for ( i = 0; i < 3; i++)
-
{
-
showDebt(zippy[i]);
-
}
-
cout << "Total debt : $" << sumDebts(zippy, 3) << endl;
-
return;
-
}
-
void another(void)
-
{
-
using pers::Person;
-
Person collector = { "Milo", "Rufsift" };
-
pers::showPerson(collector);
-
std::cout << std::endl;
-
}
运行结果:
9.3.3
文章来源: kings.blog.csdn.net,作者:人工智能博士,版权归原作者所有,如需转载,请联系作者。
原文链接:kings.blog.csdn.net/article/details/97239307
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)