0
#include <iostream> using namespace std; class Cube { int w,l,d; public: Cube(int w, int l, int d) : w(w), l(l), d(d){} int getWidth() const {return w;} int getLength() const {return l;} int getDepth() const {return d;} }; ostream& operator<< (ostream&os, const Cube& c) { os << "( " << c.getWidth() << ", " << c.getLength() << ", " << c.getDepth() << ")"; return os; } Cube operator+ (Cube& c1, Cube& c2) { int n = c1.getWidth() * c1.getDepth() * c1.getLength(); int d = c2.getWidth() * c2.getDepth() * c2.getLength(); int t = n + d; return Cube(t); } int main() { Cube c1(3,5,9), c2(2,1,4); cout << c1 << endl; cout << c2 << endl; cout << "Total Volume: " << c1 + c2; } 

In my operator+ there are some mistakes which I couldn't find out. The operator overloading for ( + ) should add up two cubes which will result in summing up of the volume of both cubes.

What should I do to my operator overloading for ( + ) ?

6
  • 1
    You don't have a constructor that takes a single parameter for Cube(t), so I guess the "mistake" is you forgot to write one? Commented Sep 14, 2014 at 5:51
  • Look at the return Cube(t); What are you returning in this case? You'r constructor is of the form Cube(int, int, int) Commented Sep 14, 2014 at 5:52
  • 1
    It it's actually a cube, and not just a general cuboid, why does it have 3 separate values to represent width, length and depth? It just needs one, since the definition of a Cube demands that they are all the same. Commented Sep 14, 2014 at 5:55
  • What if I am not allowed to change the constructor ? What should I do to my operator overloading (+) ? @WhozCraig Commented Sep 14, 2014 at 5:56
  • @user3141403: Change it to call the constructor that Cube actually has. The one with 3 arguments. Commented Sep 14, 2014 at 6:01

1 Answer 1

1

If you want to get the total volume of both cubes with operator +, you should return int instead of Cube object, you can't possibly use cout with Cube anyway. You can do this

int operator+ (Cube& c1, Cube& c2) { int n = c1.getWidth() * c1.getDepth() * c1.getLength(); int d = c2.getWidth() * c2.getDepth() * c2.getLength(); return n + d; } 
Sign up to request clarification or add additional context in comments.

2 Comments

also, take the arguments by const reference, since they are not being modified
If you're going to use int all the way, just return int

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.