Operator Overloading: Ostream/Istream

萝らか妹 提交于 2019-12-11 07:23:59

问题


I'm having a bit of trouble with a lab assignment for my C++ class.

Basically, I'm trying to get the "cout << w3 << endl;" to work, so that when I run the program the console says "16". I've figured out that I need to use an ostream overload operation but I have no idea where to put it or how to use it, because my professor never spoke about it.

Unfortunately, I HAVE to use the format "cout << w3" and not "cout << w3.num". The latter would be so much quicker and easier, I know, but that's not my decision since the assignment necessitates I type it in the former way.

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: how can I make the "cout << w3" line in main.cpp work by overloading the ostream operation?

Thanks in advance!


回答1:


Make a friend function in your class

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

define it as :

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

See here




回答2:


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



回答3:


Alternately, make a to_string method that converts weight.num to string ;-)



来源:https://stackoverflow.com/questions/19167404/operator-overloading-ostream-istream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!