C++ 重载命名空间中定义的类的ostream运算符(<;<;)
以bar.h为例:C++ 重载命名空间中定义的类的ostream运算符(<;<;),c++,namespaces,operator-overloading,ostream,C++,Namespaces,Operator Overloading,Ostream,以bar.h为例: #包括 名称空间foo{ 分类栏{ 公众: friend std::ostream&operator问题: 这是解决这个问题的正确方法吗 答复: 是的,这是解决问题的正确方法 问题: 这种方法不是透露了实现的细节吗 答复: 一点也不 线路 friend std::ostream& operator <<(std::ostream& output, const Bar&); 由于类栏是foo名称空间的一部分,因此需要在同一名称空间中定义函数
#包括
名称空间foo{
分类栏{
公众:
friend std::ostream&operator问题:
这是解决这个问题的正确方法吗
答复:
是的,这是解决问题的正确方法
问题:
这种方法不是透露了实现的细节吗
答复:
一点也不
线路
friend std::ostream& operator <<(std::ostream& output, const Bar&);
由于类栏是foo名称空间的一部分,因此需要在同一名称空间中定义函数
如果您担心隐藏实现细节,您仍然可以在bar.cc中定义函数
bar.cc
#include "foo.h"
namespace foo
{
std::ostream& operator<<(std::ostream& output, const Bar &in)
{
output << "Bar x=" << in.x << std::endl;
return output;
}
}
#包括“foo.h”
名称空间foo
{
std::ostream&operator您还可以编写std::ostream&foo::operator
$ icpc -c bar.cc
bar.cc(5): error #308: member "foo::Bar::xx_" (declared at line 9 of "bar.h") is inaccessible
output << in.xx_ << std::endl;
^
compilation aborted for bar.cc (code 2)
namespace foo {
std::ostream& operator<<(std::ostream& output, const foo::Bar &in) {
output << in.xx_ << std::endl;
return output;
}
}
friend std::ostream& operator <<(std::ostream& output, const Bar&);
namespace foo
{
class Bar;
}
std::ostream& operator <<(std::ostream& output, const foo::Bar&);
namespace foo {
class Bar {
public:
friend std::ostream& operator <<(std::ostream& output, const Bar&);
private:
int xx_;
};
}
#include "foo.h"
namespace foo
{
std::ostream& operator<<(std::ostream& output, const Bar &in)
{
output << "Bar x=" << in.x << std::endl;
return output;
}
}