使用预先制作的命名空间进行范围界定(c++)
Scoping with pre-made namespace (C++)
为了避免STL中的所有内容的作用域,您可以键入
using namespace std;
为了避免只限定少量内容的作用域,您可以输入:
using std::cout;
using std::cin;
我想编写一个以相同方式工作的库。但是,我希望能够包含特定的函数集合,而不是能够包含特定的类。
例如,我写:
- 字符串函数的集合
- 数学函数集合
它们是同一个命名空间的一部分,但我可以包括我想要的块
这是一个sudo-ish代码,但我认为它明白了我的意思:
namespace Everything{
namespace StringFunctions{
void str1(string & str);
void str2(string & str);
void str3(string & str);
void str4(string & str);
void str5(string & str);
}
namespace MathFunctions {
void math1(int & num);
void math2(int & num);
void math3(int & num);
void math4(int & num);
void math5(int & num);
}
}
,那么我希望能够这样做:
#include "Everything.h"
using Everything::Stringfunctions;
int main(){
str1("string"); //this works, I can call this!
math1(111); //compile error: I've never heard of that function!
return 0;
}
显然这不起作用,我对如何划分我的库有点困惑。我不想让它们成为类,然后不得不到处使用"点运算符",但我也不想包含大量的头文件。
也许我走错了路。我希望每个人都能帮助我采取正确的方法。
编辑:
可以这样写:
using namespace Everything::Stringfunctions;
您所给出的示例中编写库的方式已经足够了。
人们可以通过使用指令using namespace Everything::Stringfunctions
从命名空间Everything::Stringfunctions
获得所有功能。
无论如何您都应该考虑将功能拆分为不同的头文件,否则您将以噩梦般的编译时间告终。也就是说,我认为using namespace Everything::Stringfunctions;
应该做这个(和多余的namespace
在一起)。
如果您使用using namespace
而不仅仅是using
,那么您想要的似乎是有效的。请看这里(程序编译并输出'5')
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 矢量下标超出SFML游戏中的范围