简介
unnamed namespace:未命名的命名空间
作用: 主要用于取代文件中的静态声明或定义(static)
c中的static
在c语言中,如果想定义一个函数仅在本文件中可见,对其他文件都不可见,我们会选择定义静态函数。
例子:假设我们需要一个函数打印一个整数a,打印出来的格式是
value: a
//header.h
#ifndef _HEADER_H
#define _HEADER_H
void printInterger(int value);
#endif
//source.cpp,用于实现header.h中的函数
#include "header.h"
#include <cstdio>
#include <iostream>
static void format(int value, char* out)
{
std::sprintf(out, "value: %d", value);
}
void printInterger(int value)
{
char buffer[50];
format(value, buffer);
std::cout << buffer << "\n";
}
//main.cpp
#include "header.h"
int main()
{
printInterger(20);
return 0;
}
//>输出结果
value: 20
注意:我们在source.cpp
中定义了一个静态函数
static void format(int value, char* out);
,主要用于格式化字符串,又不希望其他源文件可以使用这个函数(也就是说该函数只在本文件中可见,其他文件不知道这个函数的存在,也无法使用这个函数),所以我们定义成了静态函数。
c++中的unnamed namespace
c++中的unamed namespace(未命名的命名空间)就是为了完成与static同样的作用。
在文件中进行静态声明的做法已经被C++标准取消,现在的做法是使用未命名的命名空间。--《c++ primer》
//header.h
#ifndef _HEADER_H
#define _HEADER_H
void printInterger(int value);
#endif
//source.cpp,用于实现header.h中的函数
#include "header.h"
#include <cstdio>
#include <iostream>
namespace { // 这就是unnamed namespace,该namespace没有名字
void format(int value, char* out)
{
std::sprintf(out, "value: %d", value);
}
}
void printInterger(int value)
{
char buffer[50];
format(value, buffer);
std::cout << buffer << "\n";
}
//main.cpp
#include "header.h"
int main()
{
printInterger(20);
return 0;
}
//>输出结果
value: 20
随便写写
可能对于刚接触编程的人会想到,我们直接在源文件定义一些函数,但是不在头文件显示这些函数的声明,其他文件是否可以使用这些函数呢?
答案:通过某些extern 声明之后可以使用
//header.h
#ifndef _HEADER_H
#define _HEADER_H
void printInterger(int value);
#endif
//source.cpp,用于实现header.h中的函数
#include "header.h"
#include <cstdio>
#include <iostream>
void format(int value, char* out)
{
std::sprintf(out, "value: %d", value);
}
void printInterger(int value)
{
char buffer[50];
format(value, buffer);
std::cout << buffer << "\n";
}
//main.cpp
/*现在我们将static 或 unnamed namespace 去掉了,如果
我们想使用format函数,可以在main.cpp中直接声明这个函数,然后就可以直接使用了
*/
#include "header.h"
extern void format(int value, char* out);
int main()
{
char buffer[50];
format(34,buffer);//此处可以直接调用了
printInterger(20);
return 0;
}
网友评论