我想operator<<为我的班级超载.我应该将这个重载的定义添加到std命名空间吗?(因为它ostream operator<<是std命名空间的一部分)或者我应该把它留在全局命名空间中?
简而言之:
class MyClass {
};
namespace std {
ostream& operator<< ( ostream& Ostr, const MyClass& MyType ) {}
}
Run Code Online (Sandbox Code Playgroud)
要么
class MyClass {
};
std::ostream& operator<< ( std::ostream& Ostr, const MyClass& MyType ) {}
Run Code Online (Sandbox Code Playgroud)
哪个更合适,为什么?在此先感谢您的回复.
有人可以向我解释来自 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;
}
Run Code Online (Sandbox Code Playgroud)
我得到(来自 g++ (6.3.0) 但不是来自 clang++ (3.8.1) 而不是(感谢 Robert.M)来自 Visual Studio(2017 社区))这个警告
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: …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
#include <iostream>
#include <vector>
namespace X {
std::ostream& operator<<(std::ostream& os,const std::vector<double>& v){
for (int i=0;i<v.size();i++){os << v[i] << " ";}
return os;
}
namespace Y {
struct A {std::vector<double> x;};
std::ostream& operator<<(std::ostream& os,const A& a){
os << a.x << std::endl;
return os;
}
}
}
using namespace X;
int main(int argc, char** argv) {
std::vector<double> v(10,0);
std::cout << v << std::endl;
Y::A a;
std::cout << a << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一个重载是有效的,但第二个没有.由于某种原因,它找不到第一个.我收到错误:
no match for 'operator<<' (operand types are …Run Code Online (Sandbox Code Playgroud) 我正在尝试为另一个命名空间中定义的类型T定义一个等于运算符,然后使用相等运算符optional<T>.在clang(Apple LLVM 9.1.0)上,此代码:
namespace nsp {
struct Foo {
};
}
bool operator==(const nsp::Foo& a, const nsp::Foo& b);
void foo() {
optional<nsp::Foo> a = none;
optional<nsp::Foo> b = none;
if (a == b)
;
}
Run Code Online (Sandbox Code Playgroud)
导致错误:
/usr/local/include/boost/optional/detail/optional_relops.hpp:29:34: error: invalid operands to binary expression ('const nsp::Foo' and 'const nsp::Foo')
{ return bool(x) && bool(y) ? *x == *y : bool(x) == bool(y); }
~~ ^ ~~
MWE.cpp:40:19: note: in instantiation of function template specialization 'boost::operator==<what3words::engine::nsp::Foo>' requested here
if (a …Run Code Online (Sandbox Code Playgroud)