C++命名空间与模块化
2026/6/16 22:31:07 网站建设 项目流程

C++命名空间与模块化

命名空间是C++组织代码、避免名称冲突的机制。合理使用命名空间可以提高代码的可维护性和模块化程度。

命名空间基本用法使用namespace关键字定义。

#include
#include
#include

namespace math {
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

namespace advanced {
double power(double base, int exp) {
double result = 1.0;
for (int i = 0; i < exp; ++i) result *= base;
return result;
}

double sqrt(double x) {
double guess = x / 2.0;
for (int i = 0; i < 10; ++i) {
guess = (guess + x / guess) / 2.0;
}
return guess;
}
}
}

void namespace_basics() {
std::cout << "10 + 20 = " << math::add(10, 20) << "\n";
std::cout << "5 * 6 = " << math::multiply(5, 6) << "\n";
std::cout << "2^10 = " << math::advanced::power(2.0, 10) << "\n";
std::cout << "sqrt(2) = " << math::advanced::sqrt(2.0) << "\n";
}

using声明引入特定名称。

void using_declaration() {
using math::add;
using math::advanced::power;

std::cout << "add: " << add(100, 200) << "\n";
std::cout << "power: " << power(3.0, 4) << "\n";
}

using指令引入整个命名空间。

namespace graphics {
void render() { std::cout << "Graphics render\n"; }
}

namespace audio {
void render() { std::cout << "Audio render\n"; }
}

void using_directive() {
using namespace graphics;
render();

audio::render();
}

命名空间别名简化长命名空间。

namespace company_project_module {
class Widget {
public:
void process() { std::cout << "Process widget\n"; }
};
}

void alias_demo() {
namespace cpm = company_project_module;
cpm::Widget w;
w.process();
}

匿名命名空间实现内部链接。

namespace {
int internal_counter = 0;
void internal_function() {
++internal_counter;
std::cout << "Internal count: " << internal_counter << "\n";
}
}

void anonymous_demo() {
internal_function();
internal_function();
}

内联命名空间用于版本管理。

namespace library {
inline namespace v2 {
class API {
public:
void execute() { std::cout << "v2 API\n"; }
};
}

namespace v1 {
class API {
public:
void execute() { std::cout << "v1 API\n"; }
};
}
}

void inline_namespace_demo() {
library::API api;
api.execute();

library::v1::API old_api;
old_api.execute();
}

命名空间可以分散定义。

namespace data {
struct User {
std::string name;
int age;
};
}

namespace data {
struct Product {
std::string name;
double price;
};
}

void distributed_namespace() {
data::User u{"Alice", 30};
data::Product p{"Widget", 9.99};
std::cout << u.name << " bought " << p.name << "\n";
}

ADL(参数依赖查找)允许不带命名空间调用函数。

namespace util {
struct Point { int x, y; };
void print(const Point& p) {
std::cout << "(" << p.x << "," << p.y << ")\n";
}
}

void adl_demo() {
util::Point p{10, 20};
print(p);
}

命名空间别名在函数内部更安全。

void safe_alias() {
namespace m = math::advanced;
std::cout << m::sqrt(16.0) << "\n";
}

命名空间是C++代码组织的基础,合理使用可以提高代码的可维护性和可读性。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询