c++ - 关于重新声明友元函数的警告
问题描述
我有啊,我有
#ifndef _FOO_
#define _FOO_
namespace FOO {
const std::string& getName();
}
#endif
在 Bh 我有
#ifndef _BAR_
#define _BAR_
namespace FOO {
//forward declaration
const std::string& getName();
}
namespace BAR {
class Baz {
private:
static std::string& get();
public:
friend const std::string& FOO::getName();
}
}
#endif
在 B.cpp
#include "B.h"
namespace BAR {
std::string& Baz::get() {
static std::string s;
return s;
}
}
在 A.cpp 中:
#include "A.h"
#include "B.h"
namespace FOO {
const std::string& getName() {
return BAR::Baz::get();
}
}
当我编译时,我收到来自 GCC 的以下警告:
'const string& FOO::getName()' 在同一范围内的冗余重新声明。[-Wredundant-decls]
在 A.cpp 编译期间,警告是针对 Ah 的。怎么来的?
解决方案
在 A.cpp 编译期间,警告是针对 Ah 的。怎么来的?
警告消息解释了其存在的原因。你不必要地声明FOO::getName
了两次。第二个声明称为重新声明。
解决方案:与其手动重新声明其他头的内容,#include
不如将 Ah 放入 Bh 的包含守卫中,将防止多余的重新声明。
PS 您使用的标头保护宏保留给语言实现。因此,程序的行为将是未定义的。
推荐阅读
- apache-camel - 使用带有代理和 sslcontext 的 Camel-http4 时出现 HTTP 401 错误
- android - 如何使用 navGraph 范围初始化 viewModel
- python - 将变量从无重新分配到值python
- sql-server - sp_xp_cmdshell_proxy_account 为多个需要在没有系统管理员的情况下运行 xp_cmdshell 的用户提供权限
- machine-learning - 我们如何在没有 bpe 的情况下使用 fairseq 的翻译功能
- amazon-web-services - AWS 控制台到 github
- ionic4 - 如何隐藏主页底部标签栏菜单内的后退按钮。- 离子 4
- java - jakarta.xml.bind.ContextFinder.handleClassCastException 处的 java.lang.NullPointerException
- sharepoint - 当共享点库视图为空时,有没有办法不显示任何内容?
- javascript - 如何监视类对象内部调用的函数