Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 重载命名空间中定义的类的ostream运算符(<;<;)_C++_Namespaces_Operator Overloading_Ostream - Fatal编程技术网

C++ 重载命名空间中定义的类的ostream运算符(<;<;)

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名称空间的一部分,因此需要在同一名称空间中定义函数

以bar.h为例:

#包括
名称空间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;
}

}