C++基础 命名空间

这里直接介绍怎么使用

引发

当使用using namespace std; 有没有那么一瞬间为什么要加这个,加了有什么作用呢?自己能不能定义呢?

标准C++库的所有的标识符都是在一个名为std的命名空间中定义的,或者说标准头文件(如iostream)中函数、类、对象和类模板是在命名空间 std中定义的

自己定义命名空间

定义

用namespace修饰,接命名空间的名字
namespace mystdh{

}

使用

需要在函数中声明 using namespace mystdh(开始我加在了与std命名空间相同的位置,发现会一直报xxx未定义);

示例

Longest.h

#ifndef __LONGEST_H_
#define __LONGEST_H_

using namespace std;

namespace mystdh{
class Longest{
	public:
		int Longest_Sub(string str);
};
}
#endif

Longest.cpp

#include <iostream>
#include "Longest.h"
namespace mystdh{
int Longest
::Longest_Sub(string str)
{
	cout<<"string: "<<str<<endl;
	return 0;	
}
}

main.c

#include <iostream>
#include "Longest.h"
using namespace std;
namespace mystd{
	int mt = 1;
}
int main()
{
	using namespace mystd;
	using namespace mystdh;
	Longest p;
	p.Longest_Sub("adbabcda");
	cout<<"mt:"<<mt<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LHshooter/article/details/88261557
今日推荐