The personnel department of the school kept some data about the students (school number, name, age, address), and the academic department also saved the students ' other data (student number, name, gender, achievement), and the two departments wrote the department's student Data management program, which all used Student as the class name. It is now required to call student data from both departments in the school's Student data management program, outputting student data for both. Requires programming in C + + , using namespaces.
Solution: A namespace is a user-named scope used to handle common conflicting names in a program.
Namespace :: namespace member name
Program:
Header1.h
#pragma once
#include <string>
Namespace Student1
{
Class Student
{
Public
Student (int n, string nam, int a,string addr)
{
num = n;
name = Nam;
age = A;
address = addr;
}
void Show_data ();
Private
int num;
String name;
int age;
string address;
};
void Student::show_data ()
{
cout << num: << num << ' name: ' << name << ' Age: ' << age << ' Address: ' <& Lt Address << Endl;
}
}
Header2.h
#pragma once
#include <string>
Namespace Student2
{
Class Student
{
Public
Student (int n, String nam, char S, float SCO)
{
num = n;
name = Nam;
sex = s;
Score = SCO;
}
void Show_data ();
Private
int num;
String name;
char sex;
Float score;
};
void Student::show_data ()
{
cout << "num:" << num << "name:" << name << "Sex:" << sex << "Score:" << ; Score << Endl;
}
}
Main file (main)
#include <iostream>
using namespace Std;
#include "Header1.h"
#include "Header2.h"
using namespace Student1;
int main ()
{
Student STUD1 (1001, "Wang", "123 Beijing Road,shanghai");
Stud1.show_data ();
Student2::student stud2 (1102, "Li", ' F ', 89.5);
Stud2.show_data ();
System ("pause");
return 0;
}
Operation Result:
num:1001 Name:wang age:18 address:123 Beijing Road,shanghai
num:1102 Name:li sex:f score:89.5
Please press any key to continue ...
This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1753964
The role of namespaces and programming examples