You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中Double类模板化运算符重载复用方案咨询(基于Relation类)

我来帮你搞定这个Double类的实现!根据你说的需求——复用加减运算符的逻辑,只通过不同的Relation对象(Plus/Minus)来区分操作,我们可以用策略模式来优雅地实现,下面是一步步的代码和解释:

第一步:定义Relation基类及具体运算子类

先封装加减的核心逻辑,把加法和减法抽象成Relation的子类,这样Double类的加减运算符就能复用相同的调用逻辑,只需要传入不同的Relation实例:

#include <stdexcept>

// 抽象基类:封装二元运算的核心逻辑
class Relation {
public:
    virtual double calculate(double a, double b) const = 0;
    virtual ~Relation() = default; // 虚析构确保子类资源正确释放
};

// 加法运算子类
class Plus : public Relation {
public:
    double calculate(double a, double b) const override {
        return a + b;
    }
};

// 减法运算子类
class Minus : public Relation {
public:
    double calculate(double a, double b) const override {
        return a - b;
    }
};
第二步:实现Double类及运算符重载

Double类持有内置double成员,加减运算符通过调用公共辅助函数复用逻辑,乘除则直接实现:

class Double {
private:
    double value;

    // 私有辅助函数:复用加减的公共逻辑
    Double operate(const Double& other, const Relation& relation) const {
        return Double(relation.calculate(this->value, other.value));
    }

public:
    // 构造函数:支持默认初始化
    Double(double val = 0.0) : value(val) {}

    // 获取内部存储的double值
    double getValue() const { return value; }

    // 重载+运算符:使用Plus实例完成计算
    Double operator+(const Double& other) const {
        static Plus plus_op; // 静态对象避免重复创建,提升效率
        return operate(other, plus_op);
    }

    // 重载-运算符:使用Minus实例完成计算
    Double operator-(const Double& other) const {
        static Minus minus_op;
        return operate(other, minus_op);
    }

    // 重载*运算符:直接实现乘法逻辑
    Double operator*(const Double& other) const {
        return Double(this->value * other.value);
    }

    // 重载/运算符:添加除零检查
    Double operator/(const Double& other) const {
        if (other.value == 0.0) {
            throw std::invalid_argument("Division by zero is not allowed.");
        }
        return Double(this->value / other.value);
    }

    // 可选:重载转换为原生double的运算符,方便和原生类型交互
    operator double() const {
        return value;
    }
};
第三步:使用示例

你可以像这样测试Double类的所有运算符:

#include <iostream>

int main() {
    Double a(10.5), b(3.2);

    Double sum = a + b;
    Double diff = a - b;
    Double product = a * b;
    Double quotient = a / b;

    std::cout << "Sum: " << sum.getValue() << std::endl;
    std::cout << "Difference: " << diff.getValue() << std::endl;
    std::cout << "Product: " << product.getValue() << std::endl;
    std::cout << "Quotient: " << quotient.getValue() << std::endl;

    // 和原生double交互的示例
    double native_result = sum + 2.5;
    std::cout << "Sum + 2.5: " << native_result << std::endl;

    return 0;
}
额外说明
  • 用静态的Plus/Minus对象,避免每次调用运算符都创建新实例,节省资源
  • 辅助函数operate完全复用了加减的调用逻辑,符合DRY(Don't Repeat Yourself)原则
  • 重载operator double()后,Double对象可以直接和原生double类型混合运算,兼容性更强

内容的提问来源于stack exchange,提问作者spacerong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:43:51