Skip to content

C++ 命名空间

命名空间(namespace)是 C++ 中用于组织代码和避免命名冲突的机制。它允许将相关的标识符(如变量、函数、类等)组织在一起。

1. 命名空间的基本概念

命名空间提供了一个作用域,其中的标识符在该作用域内是唯一的。

1.1 基本语法

cpp
namespace 命名空间名 {
    // 变量、函数、类等
}

示例

cpp
#include <iostream>

namespace MyNamespace {
    int x = 10;
    
    void print() {
        std::cout << "Hello from MyNamespace" << std::endl;
    }
}

int main() {
    std::cout << MyNamespace::x << std::endl;
    MyNamespace::print();
    
    return 0;
}

2. 命名空间的定义

2.1 基本定义

cpp
#include <iostream>

namespace FirstNamespace {
    int x = 10;
    
    void func() {
        std::cout << "FirstNamespace::func()" << std::endl;
    }
}

namespace SecondNamespace {
    int x = 20;
    
    void func() {
        std::cout << "SecondNamespace::func()" << std::endl;
    }
}

int main() {
    std::cout << FirstNamespace::x << std::endl;
    FirstNamespace::func();
    
    std::cout << SecondNamespace::x << std::endl;
    SecondNamespace::func();
    
    return 0;
}

2.2 嵌套命名空间

cpp
#include <iostream>

namespace Outer {
    int x = 10;
    
    namespace Inner {
        int y = 20;
        
        void print() {
            std::cout << "Outer::Inner::print()" << std::endl;
        }
    }
}

int main() {
    std::cout << Outer::x << std::endl;
    std::cout << Outer::Inner::y << std::endl;
    Outer::Inner::print();
    
    return 0;
}

2.3 分离定义命名空间

cpp
#include <iostream>

namespace MyNamespace {
    int x = 10;
}

namespace MyNamespace {
    void func() {
        std::cout << "MyNamespace::func()" << std::endl;
    }
}

int main() {
    std::cout << MyNamespace::x << std::endl;
    MyNamespace::func();
    
    return 0;
}

3. using 指令

3.1 using 声明

cpp
#include <iostream>

namespace MyNamespace {
    int x = 10;
    int y = 20;
    
    void func() {
        std::cout << "MyNamespace::func()" << std::endl;
    }
}

int main() {
    using MyNamespace::x;
    using MyNamespace::func;
    
    std::cout << x << std::endl;
    func();
    
    return 0;
}

3.2 using 指令

cpp
#include <iostream>

namespace MyNamespace {
    int x = 10;
    int y = 20;
    
    void func() {
        std::cout << "MyNamespace::func()" << std::endl;
    }
}

int main() {
    using namespace MyNamespace;
    
    std::cout << x << std::endl;
    std::cout << y << std::endl;
    func();
    
    return 0;
}

4. 命名空间别名

cpp
#include <iostream>

namespace VeryLongNamespaceName {
    int x = 10;
    
    void func() {
        std::cout << "VeryLongNamespaceName::func()" << std::endl;
    }
}

int main() {
    namespace VLN = VeryLongNamespaceName;
    
    std::cout << VLN::x << std::endl;
    VLN::func();
    
    return 0;
}

5. 匿名命名空间

匿名命名空间中的标识符只在当前文件中可见,类似于static关键字。

cpp
#include <iostream>

namespace {
    int x = 10;
    
    void func() {
        std::cout << "匿名命名空间::func()" << std::endl;
    }
}

int main() {
    std::cout << x << std::endl;
    func();
    
    return 0;
}

6. 标准命名空间

C++ 标准库中的所有标识符都定义在std命名空间中。

6.1 使用 std 命名空间

cpp
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::string name = "张三";
    std::vector<int> vec = {1, 2, 3, 4, 5};
    
    std::cout << "姓名: " << name << std::endl;
    
    for (int x : vec) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

6.2 使用 using 指令

cpp
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    string name = "张三";
    vector<int> vec = {1, 2, 3, 4, 5};
    
    cout << "姓名: " << name << endl;
    
    for (int x : vec) {
        cout << x << " ";
    }
    cout << endl;
    
    return 0;
}

7. 命名空间和类

7.1 在命名空间中定义类

cpp
#include <iostream>

namespace MyNamespace {
    class Point {
    public:
        int x;
        int y;
        
        Point(int x, int y) : x(x), y(y) {}
        
        void print() {
            std::cout << "(" << x << ", " << y << ")" << std::endl;
        }
    };
}

int main() {
    MyNamespace::Point point(10, 20);
    point.print();
    
    return 0;
}

7.2 在命名空间外定义类成员函数

cpp
#include <iostream>

namespace MyNamespace {
    class Point {
    public:
        int x;
        int y;
        
        Point(int x, int y);
        void print();
    };
}

MyNamespace::Point::Point(int x, int y) : x(x), y(y) {}

void MyNamespace::Point::print() {
    std::cout << "(" << x << ", " << y << ")" << std::endl;
}

int main() {
    MyNamespace::Point point(10, 20);
    point.print();
    
    return 0;
}

8. 示例:综合运用

现在,让我们看一个综合运用各种命名空间特性的例子:

cpp
#include <iostream>
#include <vector>
#include <string>

namespace Math {
    const double PI = 3.14159;
    
    double add(double a, double b) {
        return a + b;
    }
    
    double subtract(double a, double b) {
        return a - b;
    }
    
    double multiply(double a, double b) {
        return a * b;
    }
    
    double divide(double a, double b) {
        return a / b;
    }
}

namespace Geometry {
    class Circle {
    private:
        double radius;

    public:
        Circle(double radius) : radius(radius) {}
        
        double area() {
            return Math::PI * radius * radius;
        }
        
        double circumference() {
            return 2 * Math::PI * radius;
        }
        
        void print() {
            std::cout << "半径: " << radius << std::endl;
            std::cout << "面积: " << area() << std::endl;
            std::cout << "周长: " << circumference() << std::endl;
        }
    };
    
    class Rectangle {
    private:
        double width;
        double height;

    public:
        Rectangle(double width, double height) : width(width), height(height) {}
        
        double area() {
            return width * height;
        }
        
        double perimeter() {
            return 2 * (width + height);
        }
        
        void print() {
            std::cout << "宽: " << width << std::endl;
            std::cout << "高: " << height << std::endl;
            std::cout << "面积: " << area() << std::endl;
            std::cout << "周长: " << perimeter() << std::endl;
        }
    };
}

namespace Student {
    class Student {
    private:
        std::string name;
        int age;
        std::vector<double> grades;

    public:
        Student(std::string name, int age) : name(name), age(age) {}
        
        void add_grade(double grade) {
            grades.push_back(grade);
        }
        
        double get_average() {
            if (grades.empty()) {
                return 0.0;
            }
            
            double sum = 0;
            for (double grade : grades) {
                sum += grade;
            }
            return sum / grades.size();
        }
        
        void print() {
            std::cout << "姓名: " << name << std::endl;
            std::cout << "年龄: " << age << std::endl;
            std::cout << "平均成绩: " << get_average() << std::endl;
        }
    };
}

int main() {
    // 使用 Math 命名空间
    std::cout << "Math 命名空间:" << std::endl;
    std::cout << "PI = " << Math::PI << std::endl;
    std::cout << "10 + 20 = " << Math::add(10, 20) << std::endl;
    std::cout << "10 - 20 = " << Math::subtract(10, 20) << std::endl;
    std::cout << "10 * 20 = " << Math::multiply(10, 20) << std::endl;
    std::cout << "20 / 10 = " << Math::divide(20, 10) << std::endl;
    std::cout << std::endl;
    
    // 使用 Geometry 命名空间
    std::cout << "Geometry 命名空间:" << std::endl;
    Geometry::Circle circle(5.0);
    std::cout << "圆:" << std::endl;
    circle.print();
    std::cout << std::endl;
    
    Geometry::Rectangle rectangle(4.0, 6.0);
    std::cout << "矩形:" << std::endl;
    rectangle.print();
    std::cout << std::endl;
    
    // 使用 Student 命名空间
    std::cout << "Student 命名空间:" << std::endl;
    Student::Student student("张三", 20);
    student.add_grade(90.0);
    student.add_grade(85.0);
    student.add_grade(95.0);
    student.print();
    
    return 0;
}

小结

C++ 命名空间包括:

  1. 命名空间的基本概念

    • 命名空间提供了一个作用域
    • 用于组织代码和避免命名冲突
  2. 命名空间的定义

    • 基本定义:namespace 命名空间名 { ... }
    • 嵌套命名空间
    • 分离定义命名空间
  3. using 指令

    • using声明:using 命名空间名::标识符;
    • using指令:using namespace 命名空间名;
  4. 命名空间别名

    • 为命名空间创建别名:namespace 别名 = 命名空间名;
  5. 匿名命名空间

    • 匿名命名空间中的标识符只在当前文件中可见
  6. 标准命名空间

    • C++ 标准库中的所有标识符都定义在std命名空间中
  7. 命名空间和类

    • 在命名空间中定义类
    • 在命名空间外定义类成员函数

关键概念:

  • 命名空间:提供一个作用域,用于组织代码和避免命名冲突
  • using 声明:引入命名空间中的特定标识符
  • using 指令:引入命名空间中的所有标识符
  • 命名空间别名:为命名空间创建别名
  • 匿名命名空间:标识符只在当前文件中可见
  • std 命名空间:C++ 标准库的命名空间

掌握命名空间是编写大型 C++ 程序的重要基础,在后续章节中,我们将学习 C++ 的模板。