C++_命名空间

#include <iostream>

namespace func
{
    void swap(int &x, int &y);
    void compare(int x, int y);
    
    /*
     同一个命名空间可以在程序中出现多次,也就是说我们可以多次重复创建同一个命名空间。
     这样的重复不局限在一个文件,也就是说你可以在另一个文件中对它进行重复创建,这样我们就可以
     随时随地扩充这个命名空间的内容。
     */
    
    /*
     注意:我们应该尽量在命名空间之外定义函数,而在命名空间中只是生命函数。
     1、这样可以保持命名空间的整洁性
     2、有利于将命名空间专门存放在头文件中,而将函数的实现存放在实现文件中。
     3、命名空间中的成员都是公有的,绝对不能将它们私有化。
     4、命名空间可以嵌套,也就是说一个命名空间可以嵌套在另一个命名空间中
     */
}

void func::swap(int &x, int &y)
{
    int temp;
    std::cout << "交换前x的值:" << x << " y的值:" << y << std::endl;
    temp = x;
    x = y;
    y = temp;
    std::cout << "交换后x的值:" << x << " y的值:" << y << std::endl;
}

void func::compare(int x, int y)
{
    if (x < y)
    {
        std::cout << "x比y小!" << std::endl;
    }
    else if (x == y)
    {
        std::cout << "x等于y!" << std::endl;
    }
    else
    {
        std::cout << "x比y大!" << std::endl;
    }
}

int main()
{
    int x = 5, y = 6;
    func::swap(x,y);
    func::compare(5,6);
    
    return 0;
}
#include <iostream>

namespace func
{
    class num  // 在命名空间中可以放任何东西,包括类、对象、函数、变量、结构体等等
    {
    public:
        num();
        ~num();
        
        void swap(int &x, int &y);
        void compare(int x, int y);
    private:
        int x;
        int y;
    };
}

//func::num::num()
//{
//    x = 0;
//    y = 0;
//}

func::num::num():x(0),y(0){}
func::num::~num()
{
    std::cout << "析构函数执行..." << std::endl;
}

void func::num::swap(int &x, int &y)
{
    int temp;
    std::cout << "交换前x的值:" << x << " y的值:" << y << std::endl;
    temp = x;
    x = y;
    y = temp;
    std::cout << "交换后x的值:" << x << " y的值:" << y << std::endl;
}

void func::num::compare(int x, int y)
{
    if (x < y)
    {
        std::cout << "x比y小!" << std::endl;
    }
    else if (x == y)
    {
        std::cout << "x等于y!" << std::endl;
    }
    else
    {
        std::cout << "x比y大!" << std::endl;
    }
}


int main()
{
    using namespace func;
    
    int x = 5, y = 6;

    num m_num;
    m_num.swap(x, y);
    m_num.compare(x, y);
    
    return 0;
}
#include <iostream>

namespace people_company_boss
{
    int x = 10;
}

namespace pcb = people_company_boss;  // 假如命名空间很长,可以给它取个别名,注意,别名不能重名

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








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值