C++中的命名空间
·
C++中的命名空间
在C++中,命名空间是用来组织代码、防止命名冲突的重要工具
定义命名空间
namespace MyNamespace { // 使用namespace关键字定义一个命名空间
int value = 42; // 命名空间中定义变量
void print() { // 命名空间中定义一个函数
std::cout << "Hello from namespace!" << std::endl;
}
class MyClass { // 命名空间中定义一个类
// 类定义
};
}
使用命名空间
方式一:作用域解析运算符::
int main() {
std::cout << MyNamespace::value << std::endl;
MyNamespace::print();
return 0;
}
方式二:using声明
int main() {
using MyNamespace::value;
using MyNamespace::print;
std::cout << value << std::endl; // 直接使用
print(); // 直接使用
return 0;
}
方式三:using指令(需慎用)
using namespace MyNamespace; // 引入整个命名空间
int main() {
std::cout << value << std::endl;
print(); //使用MyNamespace命名空间中的print()函数,如果引入其它命名空间,且其它命名空间中也有print()函数,则会混淆
return 0;
}
嵌套命名空间
namespace Outer {
int x = 10;
namespace Inner {
int y = 20;
void display() {
std::cout << "x = " << x << ", y = " << y << std::endl;
}
}
}
// 使用
Outer::Inner::display();
匿名命名空间
namespace { // 不提供命名空间名称,只有namespace关键字
int fileLocalVar = 100; // 只在当前文件可见
void helperFunction() {
// 只在当前文件可用
}
}
相当于static的替代,限制作用域在当前文件内
内联命名空间(C++11)
namespace Library {
namespace v1 {
void api() { std::cout << "v1 API" << std::endl; }
}
// 使用inline关键字
inline namespace v2 { // v2 是默认版本
void api() { std::cout << "v2 API" << std::endl; }
}
}
int main() {
Library::api(); // 使用 v2(默认)
Library::v1::api(); // 明确使用 v1
return 0;
}
内联命名空间主要用于版本控制
命名空间别名
可以为长的命名空间定义一个较短的别名
namespace very_long_namespace_name {
void function() {}
}
// 创建别名
namespace short_name = very_long_namespace_name;
int main() {
short_name::function(); // 使用别名调用
return 0;
}
std命名空间
标准库都在std命名空间内
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3};
std::cout << "Standard namespace" << std::endl;
return 0;
}
最佳实践
// 在头文件中
namespace MyLib {
class Calculator {
public:
int add(int a, int b);
};
}
// 在源文件中
namespace MyLib {
int Calculator::add(int a, int b) {
return a + b;
}
}
// 在main文件中使用时的推荐方式
int main() {
MyLib::Calculator calc; // 明确指定命名空间
int result = calc.add(5, 3);
return 0;
}
使用实例
#include <iostream>
#include <string>
namespace Geometry {
const double PI = 3.14159;
class Circle {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() { return PI * radius * radius; }
};
namespace Utils {
void printInfo(const std::string& shape) {
std::cout << "Shape: " << shape << std::endl;
}
}
}
// 命名空间别名
namespace Geo = Geometry;
int main() {
Geo::Circle circle(5.0);
std::cout << "Area: " << circle.area() << std::endl;
Geo::Utils::printInfo("Circle");
return 0;
}
更多推荐


所有评论(0)