习题 14.3 学校的人事部门保存了有关学生的部分数据(学号、姓名、年龄、住址),教务部门也保存了学生的另外一些数据(学号、姓名、性别、成绩),两个部门分别编写了本部门的学生数据管理程序,其中都用了Student作为类名。现在要求在全校的学生数据管理程序中调用这两个部门的学生数据,分别输出两种内容的学生数据。要求用C++编程,使用命名空间。
头文件 14.3.1(人事部门):
代码:
//人事部门
#include<iostream>
#include<string>
using namespace std;
namespace student1
{
class Student
{
public:
Student(int n, string na, int a, string add) :num(n), name(na), age(a), address(add) {}
void print();
private:
int num;
string name;
int age;
string address;
};
void Student::print()
{
cout << "学号:" << num << endl;
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "地址:" << address << endl;
}
}
头文件 14.3.2(教务部门):
代码:
//教务部门
#include<iostream>
#include<string>
using namespace std;
namespace student2
{
class Student
{
public:
Student(int n, string na, int a, double s) :num(n), name(na), age(a), score(s) {}
void print();
private:
int num;
string name;
int age;
double score;
};
void Student::print()
{
cout << "学号:" << num << endl;
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "成绩:" << score << endl;
}
}
主函数:
代码:
//主函数
#include<iostream>
#include"14.3.1.h"
#include"14.3.2.h"
using namespace std;
using namespace student1;
int main()
{
Student s1 = { 10001,"胡图图",6,"翻斗花园" }; //using namespace 后可以直接使用
s1.print();
cout << endl;
student2::Student s2 = { 10002,"牛爷爷",60,60 }; //通过头文件引用
s2.print();
return 0;
}
运行结果: