命名空间:People
类:Student
方法:printDemo();
Student.h
注意:当我们命名空间People里定义了一个方法时,在写该方法的实现时,一定要在方法名称之前加上命名空间。比如说:
void<em><strong><span style="color:#FF0000;"> People::</span></strong></em>printDemo()
一定有人想问为什么?否则编译时,会爆出找不到printDemo()的实现。假如说:在头文件里还定义了一个printDemo()当然了,这个方法不在命名空间People里,那么在实现该方法时,如果不写成这样:void<em><strong><span style="color:#FF0000;"> People::</span></strong></em>printDemo(){}
谁知道,您是要实现命名空间里的printDemo(),还是要实现命名空间外面的printDemo()呢?#include<string>
using namespace std;
namespace People
{
class Student
{
private:
int id;
int age;
public:
Student(int id, int age);
~Student();
void PrintInfo();
};
void printDemo();
}
Student.cpp
#pragma once
#include"Student.h"
#include<iostream>
using namespace People;
Student:: Student(int id, int age)
{
this->id = id;
this->age = age;
}
Student::~Student()
{}
void Student:: PrintInfo()
{
cout << "id" << id << "age" << age;
}
void<em><strong><span style="color:#FF0000;"> People::</span></strong></em>printDemo()
{
cout << "DDDDDDDDD" << endl;
}
main.cpp
#pragma once
#include<string>
#include"Student.h"
using namespace People;
using namespace std;
int main()
{
Student stu(1000,10);
stu.PrintInfo();
system("pause");
printDemo();
return 0;
}
【补充】
namespace Animal,class Bird,Function Fly;
【文件:functionDemo.h】
#include<iostream>
#include<algorithm>
using namespace std;
namespace Animal
{
class Bird
{
public :
void Fly();
};
void Fly();
}
void Fly();
【文件namespaceDemo.cpp】
#include"namespaceDemo.h"
using namespace Animal;
void Bird::Fly()
{
cout << "鸟在飞!!!!!"<<endl;
}
void Fly()
{
cout << "不是动物的飞机在飞!!"<<endl;
}
void Animal::Fly()
{
cout << "动物在飞!!!!"<<endl;
}
int main()
{
Bird bir;
bir.Fly();
Animal::Fly();
::Fly();
system("pause");
}