【发布时间】:2020-01-16 15:58:16
【问题描述】:
我试图理解为什么在我使用命名空间而不是显式声明命名空间附件时我的函数存在歧义。
Book.h 头文件:
#ifndef MYBOOK_BOOK_H
#define MYBOOK_BOOK_H
namespace mybook
{
void showTitle();
void showTableOfContents();
}
#endif
我的 implmenetation 文件导致歧义错误: Book.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 不起作用?
【问题讨论】:
-
永远不要使用“使用命名空间标准”。你不应该试图弄清楚如何让它发挥作用,而应该摆脱这种做法。
-
并且不要使用cstring等C头文件。使用字符串和 C++ 中的适当工具。
-
Eric 评论的一些背景:stackoverflow.com/questions/1452721/… 请注意,有些人不同意您应该永远使用
using namespace std的想法。 -
@Rosme 虽然首选
std::string而不是C 字符串是一个好建议,但通常不使用C 头文件并不是一个好建议。例如,使用来自<cmath>、<cstdint>、<cstddef>和许多其他的东西没有任何问题。在 OP 的情况下(尽管它目前未使用)<cctype>也有有效用途,因为它提供的大多数功能都没有 C++ 等价物。 -
@walnut 真的。我不应该那样说。
标签: c++ namespaces declaration definition name-lookup