c++ - 使用命名空间与使用命名空间闭包的范围

标签 c++ namespaces declaration definition name-lookup

我试图理解为什么当我使用 using 命名空间而不是显式声明命名空间外壳时我的函数存在歧义。

Book.h 头文件:

#ifndef MYBOOK_BOOK_H
#define MYBOOK_BOOK_H 

namespace mybook
{
    void showTitle();
    void showTableOfContents();
}

#endif

我的实现文件导致歧义错误:
书.cpp
#include "Book.h"
#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;
using namespace mybook;

void showTitle() {
    cout << "The Happy Penguin" << endl;
    cout << "By John Smith" << endl;
}

void showTableOfContents() {
     cout << "Chapter 1" << endl;
     cout << "Chapter 2" << endl;
}


我的实现文件没有歧义错误:
书.cpp
#include "Book.h"
#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

namespace mybook {

   void showTitle() {
       cout << "The Happy Penguin" << endl;
       cout << "By John Smith" << endl;
   }

   void showTableOfContents() {
        cout << "Chapter 1" << endl;
        cout << "Chapter 2" << endl;
   }
}

我认为 Book.cpp 的第一个场景应该可以工作,因为通过在开头声明 using namespace mybook 是说我现在要实现我在头文件中定义的函数。但是,我收到了“错误‘showTitle’:对重载函数的模棱两可的调用可能是‘void showTitle(void) 或 void mybook::showTitle(void)’”的错误,对于我的其他函数 showTableOfContents 也是如此。为什么在第一个场景中使用命名空间 mybook 不起作用?

最佳答案

I would think that the first scenario of Book.cpp should work because by declaring using namespace mybook at the beginning it is saying that I am now going to implement the functions I defined in the header file.



那就是你不正确的地方。 using namespace mybook;说你正在使用来自 mybook 的名字,并不是您要为 mybook 定义/添加名称.在 mybook 中定义名称您需要像在第二个示例中一样打开命名空间并将定义放入其中。

关于c++ - 使用命名空间与使用命名空间闭包的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773471/

相关文章:

C++ 和 DLL 未在此范围内声明

c++ - 在 MPI 中跟踪全局索引

c++ - std::function 隐式类型转换

actionscript - 如何访问 Flex Builder Actionscript 项目中的 'mx' 或 'fl' 命名空间?

c++ - C++ 和 OpenCV 中多个对象的 vector 和原始类型的 vector

c++ - 为什么匿名命名空间优于静态全局变量?

php - 似乎无法正确使用 PHP 命名空间

c - 通过宏将变量声明为内联函数

c++ - 在 C++ 中使用依赖于函数的大小初始化数组

c++ - 如何避免重复包含头文件