代码之家  ›  专栏  ›  技术社区  ›  ereOn

运算符重载和命名空间[重复]

  •  11
  • ereOn  · 技术社区  · 14 年前

    可能重复:
    Where should non-member operator overloads be placed?

    在浏览So时,我经常会发现涉及重载/定义 std::ostream& operator<<(std::ostream& os, const Foo& foo) 或A Foo operator+(const Foo& l, const Foo& r) .

    虽然我知道如何以及何时(不)编写这些运算符,但我对 namespace 事情。

    如果我有以下课程:

    namespace bar
    {
      class Foo {};
    }
    

    在哪儿 命名空间 我应该写不同的运算符定义吗?

    // Should it be this
    
    namespace bar
    {
      std::ostream& operator<<(std::ostream& os, const Foo& foo);
    }
    
    // Or this ?
    
    namespace std
    {
      ostream& operator<<(ostream& os, const bar::Foo& foo);
    }
    
    // Or this ?
    
    std::ostream& operator<<(std::ostream& os, const bar::Foo& foo);
    

    同样的问题也适用于 operator+ . 那么,这里的好做法是什么? 为什么? ?

    5 回复  |  直到 14 年前
        2
  •  13
  •   Sjoerd    14 年前

      ::std::ostream& os = /* something */;
      const ::bar::Foo& foo = /* something */;
      os << foo;
    

    namespace bar   
    {   
      std::ostream& operator<<(std::ostream& os, const Foo& foo);   
    }   
    
        3
  •  2
  •   James Kanze    14 年前

        4
  •  0
  •   Armen Tsirunyan    14 年前

    namespace N
    {
       class X(){};
       void f(X){}
    }
    int main()
    {
        N::X x;
        f(x); //works fine, no need to qualify f like N::f
    }
    

        5
  •  0
  •   Bart van Ingen Schenau    14 年前

    operator+ operator<< operator>> std bar