注册 登录
编程论坛 C++教室

两个文件其中的namespace的含义 求解答

新人学习 发布于 2018-01-16 11:17, 1032 次点击
//第一个文件
#include<iostream>
using namespace std;
void other();
void another();
int x = 10;
int y;

int main()
{
    cout << x << endl;
    {
        int x = 4;
        cout << x << endl;
        cout << y << endl;
    }
    other();
    another();

    system("pause");
    return 0;
}
void other()
{
    int y = 1;
    cout << "Other: " << x << ", " << y << endl;
}
//第二个文件
#include<iostream>
using namespace std;
extern int x;
namespace
{
    int y = -4;

}

void another()
{
    cout << "another(): " << x << ", " << y << endl;
}

//为什么最后一行输出Y的值是-4?namespace 起到了什么作用????

[此贴子已经被作者于2018-1-16 11:19编辑过]

3 回复
#2
yangfrancis2018-01-16 22:14
输出-4确实有些奇怪,目测应该根本运行不起来的。
#3
rjsp2018-01-16 22:47
回复 2楼 yangfrancis
namespace
{
    int y = -4;
}
相当于C语言的
static int y = -4;
#4
yangfrancis2018-01-18 12:23
原来这样。我还以为namespace后面一定要有个空间名称才行。
1