namspace学习笔记

1. 为什么要用namespace?

为了解决名称的冲突问题,假设同一个班级有两个人叫李华,老师为了区分他们,可能将称呼他们为大李华和小李华;同样的,在程序中为了区分相同名称的变量、函数等,需要引入namespace关键字

namespace test1
{
    int age = 22;
}

namespace test2
{
    int age = 30;
}

2. 常用语法

  • 在命名空间中写函数以及变量
  • 在命名空间内写函数声明,命名空间外定义需要加 ::
#include <iostream>

using namespace std;

namespace test1
{
    int age = 100;
    void show();
}

void test1::show()
{
    cout << age << endl;
}


int main()
{
    test1::show();

    system("pause");
    return 0;
}

  • 在命名空间里写类,在头文件中创建命名空间并在其中声明类,在源文件中首先声明命名空间,然后定义类
#include <iostream>

using namespace std;

namespace test
{
    class Person
    {
    private:
        int m_a;
    public:
        Person(int a);
        ~Person();
        void show();
    };
}

#include "namespace.h"

using namespace std;
using namespace test;  //前置声明

Person::Person(int a)
{   
    this->m_a = a;
}

Person::~Person(){}

void Person::show()
{
    cout << m_a << endl;
}

int main()
{
    Person p(12);
    p.show();

    system("pause");
    return 0;
}

  • 命名空间是开放的,随时可以加入新成员
#include "namespace.h"

using namespace std;
using namespace test;  //前置声明

Person::Person(int a)
{   
    this->m_a = a;
}

Person::~Person(){}

void Person::show()
{
    cout << m_a << endl;
}

//加入新的成员
namespace test 
{
    class Student
    {
    private:
        char * m_name;
    public:
        Student(char * name):m_name(name)
        {
            cout << m_name << endl;
        }
        ~Student(){}
    };
    
}
int main()
{
    Person p(12);
    p.show();

    Student s("james");

    system("pause");
    return 0;
}

  • 命名空间可以嵌套
namespace test 
{
    class Student
    {
    private:
        char * m_name;
    public:
        Student(char * name):m_name(name)
        {
            cout << m_name << endl;
        }
        ~Student(){}
    };

    //命名空间的嵌套
    namespace test1
    {
        int a = 22;
    } // namespace test1
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值