#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;
}
在我的 operator+ 中有一些我找不到的错误。 ( + ) 的运算符重载应该将两个立方体相加,这将导致两个立方体的体积相加。
我应该如何处理 ( + ) 的运算符重载?
最佳答案
如果你想用运算符 + 得到两个立方体的总体积,你应该返回 int 而不是 Cube 对象,无论如何你不可能对 Cube 使用 cout。你可以这样做
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;
}
关于c++ - + 的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25830468/