【问题标题】:Operator Overloading: Ostream/Istream运算符重载:Ostream/Istream
【发布时间】:2013-10-10 15:16:08
【问题描述】:

我的 C++ 课程的实验作业有点麻烦。

基本上,我正在尝试获取“cout

不幸的是,我必须使用格式“cout

main.cpp:

#include <iostream>
#include "weight.h"

using namespace std;
int main( ) {

    weight w1(6);
    weight w2(10);
    weight w3;

    w3=w1+w2;
    cout << w3 << endl;
}

重量.h:

#ifndef WEIGHT_H
#define WEIGHT_H

#include <iostream>

using namespace std;

class weight
{
public:
    int num;
    weight();
    weight(int);
    weight operator+(weight);

};

#endif WEIGHT_H

重量.cpp:

#include "weight.h"
#include <iostream>

weight::weight()
{

}

weight::weight(int x)
{
    num = x;
}

weight weight::operator+(weight obj)
{
    weight newWeight;
    newWeight.num = num + obj.num;
    return(newWeight);
}

TL;DR:如何通过重载 ostream 操作使 main.cpp 中的“cout

提前致谢!

【问题讨论】:

    标签: c++ operator-overloading overloading istream ostream


    【解决方案1】:

    在你的班级里结交朋友

    friend ostream &amp; operator &lt;&lt; (ostream&amp; ,const weight&amp;);

    定义为:

    ostream & operator << (ostream& os,const weight& w)
    {
      os<<w.num;
      return os;
    }
    

    here

    【讨论】:

      【解决方案2】:
      class weight
      {
      public:
          int num;
          friend std::ostream& operator<< (std::ostream& os, weight const& w)
          {
              return os << w.num;
          }
          // ...
      };
      

      【讨论】:

        【解决方案3】:

        或者,创建一个将 weight.num 转换为字符串的 to_string 方法;-)

        【讨论】:

          猜你喜欢
          • 2020-02-10
          • 2011-08-31
          • 2016-07-28
          • 2021-12-16
          • 1970-01-01
          • 2011-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多