我试图理解为什么当我使用 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/