Muddy
Muddy

Reputation: 87

Operator Overloading: Ostream/Istream

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!

Upvotes: 1

Views: 2638

Answers (3)

ChuckCottrill
ChuckCottrill

Reputation: 4444

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

Upvotes: 0

P0W
P0W

Reputation: 47854

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

Upvotes: 2

David G
David G

Reputation: 96855

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

Upvotes: 0

Related Questions