析觇啊 发表于 2020-4-23 15:33:06

关于重载C++的<<运算符

本帖最后由 析觇啊 于 2020-4-23 23:02 编辑

#include <iostream>

class MyInt
{
      friend std::ostream& operator << (std::ostream& out, const MyInt &myint);

public:
      MyInt()
      {
                m_num = 0;
      }

      MyInt& operator++ ();
      MyInt operator++(int);

private:
      int m_num;
};

MyInt& MyInt::operator++()
{
      this->m_num += 1;
      return *this;
}

MyInt MyInt::operator++(int)
{
      MyInt temp = *this;
      this->m_num++;
      return temp;
}

std::ostream& operator << (std::ostream& out, const MyInt &myint)
{
      out << myint.m_num;
      return out;
}

int main()
{
      MyInt myint;
      std::cout << (++(++myint)) << std::endl;

      std::cout << myint++ << std::endl;


      //myint++;
      //std::cout << myint << std::endl;
}
请问这段代码哪里有问题呢。我重载后置++后确实是返回MyInt类了呀。
而且为什么如果我按注释的46和47行就可以成功输出呢。谢谢大家!

人造人 发表于 2020-4-23 15:34:50

把代码以文本的形式贴上来,我需要复制粘贴,而不是看着图片抄一遍

人造人 发表于 2020-4-23 16:21:25

析觇啊 发表于 2020-4-23 15:38


你在 你的帖子下面回复我,我是没有通知的,除非我点进来才能知道你回复了我

#include <iostream>

class MyInt
{
      friend std::ostream& operator << (std::ostream& out, const MyInt &myint);

public:
      MyInt()
      {
                m_num = 0;
      }

      MyInt& operator++ ();
      MyInt operator++(int);

private:
      int m_num;
};

MyInt& MyInt::operator++()
{
      this->m_num += 1;
      return *this;
}

MyInt MyInt::operator++(int)
{
      MyInt temp = *this;
      this->m_num++;
      return temp;
}

std::ostream& operator << (std::ostream& out, const MyInt &myint)
{
      out << myint.m_num;
      return out;
}

int main()
{
      MyInt myint;
      std::cout << (++(++myint)) << std::endl;

      std::cout << myint++ << std::endl;


      //myint++;
      //std::cout << myint << std::endl;
}

析觇啊 发表于 2020-4-23 16:39:00

人造人 发表于 2020-4-23 16:21
你在 你的帖子下面回复我,我是没有通知的,除非我点进来才能知道你回复了我

不好意思哦,第一次提问,还不太会使用。谢谢提醒
页: [1]
查看完整版本: 关于重载C++的<<运算符