-->

运算符重载:ostream的/的IStream(Operator Overloading: Ostr

2019-10-18 17:18发布

我在与我的C ++类实验室任务有点麻烦。

基本上,我试图让“的cout << W3 << ENDL;” 工作,所以,当我运行程序控制台说:“16”。 我已经想通了,我需要使用一个ostream超负荷运转,但我不知道放在哪里或如何使用它,因为我从来没有教授谈到它。

不幸的是,我必须使用的格式“的cout << W3”,而不是“COUT << w3.num”。 后者会有那么多更快,更容易,我知道,但由于分配必要我在以前的方式键入它,这不是我的决定。

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;
}

weight.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

weight.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:我怎样才能使“COUT << W3”在main.cpp中的工作线通过重载ostream的操作?

提前致谢!

Answer 1:

让友元函数在您的类

friend ostream & operator << (ostream& ,const weight&);

其定义为:

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

见这里



Answer 2:

class weight
{
public:
    int num;
    friend std::ostream& operator<< (std::ostream& os, weight const& w)
    {
        return os << w.num;
    }
    // ...
};


Answer 3:

或者,使该weight.num转换为字符串to_string方法;-)



文章来源: Operator Overloading: Ostream/Istream