【问题标题】:Operation overloading for namespaced classes [duplicate]命名空间类的操作重载[重复]
【发布时间】:2015-10-19 01:40:42
【问题描述】:

假设我有以下课程:

namespace Example
{
    class Bar {};
}

现在,如果我想重载 Bar 类的运算符,我应该这样做:

 namespace Example
 {
    class Bar {};

    ostream& operator<<(ostream& os, const Bar& b)
    {/*..........*/}
}

或者我应该这样做:

namespace Example
{
    class Bar {};
}

ostream& operator<<(ostream& os, const Example::Bar& b)
{/*..........*/}

如果我应该做上述任何一个,请张贴解释为什么应该这样做。

附: /*.....*/ 仅表示函数的主体(为简单起见,省略)

【问题讨论】:

  • @Petr IMO,没有我的不是重复的。在您提供的链接中,它告诉我在命名空间中执行此操作,因为编译器会找到它。但是,我要问的是哪个更好,为什么?谢谢你的链接
  • @J.Alvaro.T,它还说“无需污染全局命名空间”。那里的其他答案也说同样的话(“……不要弄乱全局命名空间。”)
  • @Petr 感谢您指出这一点。大概是错过了。有时我只是浏览了一个问题而错过了重要的部分。

标签: c++ namespaces operator-overloading


【解决方案1】:
  #include<iostream>
  using namespace std;

    namespace Example
     {
        class Bar
        {//........

friend ostream& operator<<(ostream& os, const Bar& b);
};


    }

    ostream& operator<<(ostream& os, const Example::Bar& b)
        {//..........
        }

    int main() {
        Example :: Bar b;
//        out<<b;  I am not sure About this 
        return 0;
    }

希望我这次做得很好

【讨论】:

  • 但这并不能说明它应该放在命名空间的外部还是内部。
  • 这不能回答问题。
  • 当然它会回答,因为它复制了他的第二选择,他只是误认为没有使用类 Bar 引用运算符函数的定义
  • 它没有回答问题,因为代码根本不起作用。
  • @juanchopanza,为什么?
猜你喜欢
  • 2016-06-25
  • 2020-06-08
  • 2016-07-21
  • 2015-07-05
  • 2015-02-17
  • 1970-01-01
  • 2011-10-17
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多