gpt4 book ai didi

c++ - 如何正确使用 "using namespace foo?"

转载 作者:行者123 更新时间:2023-11-30 02:22:55 24 4
gpt4 key购买 nike

我对 C++ 中的 using namespace x 有点困惑。为什么在这种情况下它会不正确? “使用命名空间”是否仅适用于我们#including 的其他文件?

#include <iostream>
using namespace A;


namespace A {
void print() {

std::cout << "From namespace A" << std::endl;
}
}

namespace B {
void printB() {
std::cout << "From namespace B" << std::endl;
}
}


int main() {
print();
printB();
}

最佳答案

正如错误消息告诉您的那样here这些函数未在您当前的范围内声明。
您使用未指定命名空间调用的所有内容都被视为在全局命名空间中找到,如 ::print::printB

您需要像下面这样使用命名空间作用域运算符 (::):

A::print();
B::printB();

using 语句:

using A::print;
using B::printB;

关于c++ - 如何正确使用 "using namespace foo?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46737220/

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