在班级内部工作吗

在班级内部工作吗

本文介绍了重载运算符是否<<在班级内部工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,我试图使运算符超载<<在班级内部

I mean, I was trying to overload the operator<< inside the class

像这样

 class A {
      public:
           ostream &operator<<(ostream &os);// which doesnt work

      private:
           friend ostream &operator<<(ostream &os, const A& a); //Works
           int i;

 };

  Definition
          ostream &operator<<(ostream &os, const A& a) {
              os<<a.i;
              return os;
          }

为什么不能在特定于类的类内重载运算符?还是我错过了什么?还是我愚蠢地以这种方式思考?请告知.

why can't I overload the operator inside the class specific to class? or Am I missing something? or Am I stupid to even think in such a way? Please advise.

推荐答案

成员函数:

ostream &operator<<(ostream &os);

有用,但不适用于您想要的情况.当您执行以下操作时,它将被调用:

does work, but not for the situation you want. It will be called when you do something like:

A a;
a << std::cout;

即该对象是运算符的左侧.

i.e. where the object is the left-hand side of the operator.

这篇关于重载运算符是否&lt;&lt;在班级内部工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:42