c++基础

::作用域运算符

::双冒号为全局运算符

#include <iostream>
using namespace std;

int atk = 200;

void Test()
{
    int atk = 100;
    cout << "Test内部:" << atk << endl;
    cout << "Test外部:" << ::atk << endl;
}

int main()
{
    Test();
    system("Pause");
    return EXIT_SUCCESS;
}

结果

命名空间使用语法

命名空间只能全局范围内定义

namespace A{
    int a = 10;
}
namespace B{
    int a = 20;
}
void test(){
    cout << "A::a : " << A::a << endl;
    cout << "B::a : " << B::a << endl;
}

命名空间可嵌套命名空间

namespace A{
    int a = 10;
    namespace B{
        int a = 20;
    }
}
void test(){
    cout << "A::a : " << A::a << endl;
    cout << "A::B::a : " << A::B::a << endl;
}

命名空间是开放的,即可以随时把新的成员加入已有的命名空间中

namespace A{
    int a = 10;
}

namespace A{
    void func(){
        cout << "hello namespace!" << endl;
    }
}

void test(){
    cout << "A::a : " << A::a << endl;
    A::func();
}

声明和实现可分离

头文件

#pragma once

namespace MySpace{
    void func1();
    void func2(int param);
}

cpp文件

void MySpace::func1(){
    cout << "MySpace::func1" << endl;
}
void MySpace::func2(int param){
    cout << "MySpace::func2 : " << param << endl;
}

无名命名空间名称

意味着命名空间中的标识符只能在本文件内访问,相当于给这个标识符加上了static,使得其可以作为内部连接

namespace{
    
    int a = 10;
    void func(){ cout << "hello namespace" << endl; }
}
void test(){
    cout << "a : " << a << endl;
    func();
}

命名空间别名

namespace veryLongName{
    
    int a = 10;
    void func(){ cout << "hello namespace" << endl; }
}

void test(){
    namespace shortName = veryLongName;
    cout << "veryLongName::a : " << shortName::a << endl;
    veryLongName::func();
    shortName::func();
}
原文地址:https://www.cnblogs.com/yifengs/p/15086322.html