C++命名空間的使用

命名空間: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");
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章