gpt4 book ai didi

c++ - 我们如何访问创建它的文件之外的未命名命名空间?

转载 作者:行者123 更新时间:2023-12-04 17:05:12 24 4
gpt4 key购买 nike

我在网上阅读有关命名空间的信息,并阅读了有关未命名命名空间的信息。我读到未命名的命名空间只能在创建它们的文件中访问。但是当我自己尝试时,它并没有像那样工作。这怎么可能?
这是我所做的:
文件 1:

#include <iostream>
using namespace std;

namespace space1 {
int a = 10;
void f() {
cout << "in space1 of code 1" << endl;
};
}

namespace {
int x = 20;
void f() {
cout << "in unnamed space" << endl;
}
}
file2:我从 file1 访问命名空间的地方
#include <iostream>
#include "code1.cpp"
using namespace std;

int main() {
space1::f();
cout << space1::a;
cout << x << endl;
f();

return 0;
}

最佳答案

Can we access the unnamed namespaces outside the file they were created?


取决于您指的是哪个"file"。如果您引用头文件,那么是的,您可以访问外部的未命名命名空间,因为未命名命名空间可用于包含标题的整个翻译单元。
如果您引用整个翻译单元,则否,其他翻译单元无法访问未命名的命名空间。

关于c++ - 我们如何访问创建它的文件之外的未命名命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70299936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com