#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;
}
在我的算子+中有一些我无法找到的错误。 运算符重载(+)应该加上两个立方体,这将导致两个立方体的体积相加。
我应该怎样对我的运算符重载(+)?
答案 0 :(得分:1)
如果你想用operator +得到两个立方体的总体积,你应该返回int而不是Cube对象,你无论如何也不可能使用Cube和Cube。你可以这样做
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;
}