【发布时间】:2017-11-28 17:06:26
【问题描述】:
有人可以向我解释来自 g++ 的警告吗?
给定以下代码
#include <iostream>
namespace foo
{
struct bar
{ friend std::ostream & operator<< (std::ostream &, bar const &); };
}
std::ostream & foo::operator<< (std::ostream & o, foo::bar const &)
{ return o; }
int main ()
{
foo::bar fb;
std::cout << fb;
}
我收到(来自 g++ (6.3.0) 但不是来自 clang++ (3.8.1) 而不是来自 Visual Studio(2017 社区)的(感谢 Robert.M))这个警告
tmp_002-11,14,gcc,clang.cpp:10:16: warning: ‘std::ostream& foo::operator<<(std::ostream&, const foo::bar&)’ has not been declared within foo
std::ostream & foo::operator<< (std::ostream & o, foo::bar const &)
^~~
tmp_002-11,14,gcc,clang.cpp:7:29: note: only here as a friend
{ friend std::ostream & operator<< (std::ostream &, bar const &); };
^~~~~~~~
我知道我可以这样定义操作符
namespace foo
{
std::ostream & operator<< (std::ostream & o, bar const &)
{ return o; }
}
但是...我的初始代码有什么问题?
【问题讨论】:
-
您是否找到了解决方案或评论了为什么会这样?还有,你当初为什么把朋友放在那里?这有必要工作吗?
-
@Ilendir - 目前没有找到“解决方案”(但我不寻找“解决方案”;我要求解释); (原始的,更复杂的)代码的第一个版本不是我的,而是来自开源代码;我建议按照第二个块(
namespace foo块内的运算符)中显示的方式修改代码,但我的疑问仍然存在:为什么第一个是错误的(或危险的)? Robert.M 的回答是错误的。
标签: c++ namespaces g++ operator-overloading friend