c++ - + 的运算符重载

标签 c++ operator-overloading

#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/

相关文章:

c++ - 如何优先选择 `operator<<` 而不是通用 `operator T()` 转换?

c++ - 从 Boost C++ 库构建特定的库

c++ - 是否必须使逻辑运算符短路?和评估顺序?

c++ - QProcess 如何在 Windows 上工作

c++ - 为什么要在 lambdas 中捕获 this 以及指向 this 的共享指针?

C++ 运算符重载 : no known conversion from object to reference?

c++ - 如何给一个枚举值的索引并得到它?

operator-overloading - 如何定义 'AT-POS'方法?

c++ - 为什么在有私有(private)变量的情况下需要使引用常量?

rust - 有没有办法覆盖 Rust 类型的赋值运算符?