-1

While trying to solve Box-It challenge on Hackerrank I got stuck at overloading the operators <,<<

This is the Box struct

struct Box
{
    public:
        int l,b,h;    
        
        int getLength(void);
        int getBreadth(void);
        int getHeight(void);        
        
        long long CalculateVolume(void) ;
        
        Box operator<<(const Box& b) {
            Box box;
            box.l = this->l + b.l;
            box.b = this->b + b.b;
            box.h = this->h + b.h;
            return box;
        }
        
        
};



int Box::getLength(void) 
{
    return l;
}

int Box::getBreadth(void)
{
    return b;
}

int Box::getHeight() 
{
    return h;
}




long long Box::CalculateVolume(void) 
{
    return l*h*b;
}



Error log can be found on pastebin

RAT
  • 31
  • 5

1 Answers1

-2

Okay, there's a lot of data out there on overloading <<. The way you're doing it is wrong. The signature should be:

std::ostream & operator<<(std::ostream &out, const Box &box) {
    ...
    return out;
}

And it can't be a member method. So you define it outside the class definition.

However, your code should work if you use it for operator<.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
  • OPs `operator<<` is not the `operator<<` they want, but it is not "wrong" – 463035818_is_not_an_ai Nov 26 '21 at 22:18
  • It also doesn't fit the semantics of `operator<`. It would be a working implementation of `operator+`, however. (Assuming we agree that the "sum" of two boxes should be a box with their combined length width and height--I'm not sure how much sense that really makes, but it IS addition.) – Nathan Pierson Nov 26 '21 at 22:19