重载纯虚操作符

Tov*_*sch 3 c++ abstract-class operator-overloading derived-class pure-virtual

我有一个Number带有 4 个纯虚运算符 ( +, -, /, *) 的抽象类。我想提出两个派生类IntegerReal并覆盖有这些运营商。我不太明白如何声明运算符。我还没有在网上找到任何与我的情况类似的例子。

我的问题是:在抽象基类中,Number我的运算符必须返回 referenceNumber&或 pointer Number*,因为我不能返回抽象类本身。但是我应该传递什么作为参数?Number&或者Number*也是,但我需要在课堂上存储数字,我的基类中应该有类似的东西void* num吗?让我们想象一下,我有

class Number {
    ...
    virtual Number& operator+(const Number&) = 0;
};
Run Code Online (Sandbox Code Playgroud)

我应该如何在派生类中覆盖这个运算符Integer

Aco*_*gua 5

我知道,但是我的导师坚持将其作为在抽象类中进行的覆盖纯虚拟运算符的覆盖,但我真的不明白。

好吧,您可以从中了解两件事:

  1. 虚函数一般是如何工作的(自定义运算符只不过是一个普通函数,只是调用语法不同)。
  2. 虚拟函数不是解决任何问题的圣杯。

问题是,这些类IntegerReal最有可能有不同的内部表现-所以你不会是能够做到无需了解您的第二个操作数收到的具体类型的加法/乘法/ ...。此外,目前还不清楚混合操作数类型的返回类型应该是什么。

我真的不需要 atm 来添加 real+int 只有 real+real, int+int

好吧,我们可以抓住这个:

class Number
{
public:
    virtual ~Number() { } // in any case, a virtual base class should have a virtual destructor!

    // fine so far:
    virtual Number& operator+(Number const&) const = 0;
    // we are not going to change the          ^
    // own instance, so we'd rather have this operator const
    // (in contrast to operator+=)
};

class Integer : public Number
{
public:
    Integer& operator+(Number const& other) const override
    // ^ co-variant return type, so that's fine
    {
        // at very first, we make sure that we actually received
        // an instance of type Integer
        auto o = dynamic_cast<Integer const*>(&other);
        if(!o)
            // if not, throwing an exception is a good candidate
            // for error handling...
            throw std::invalid_argument("argument must be of type Integer");

        // now as we know it IS an Integer:
        return Integer(this->value + o->value); // or whatever...
        // OOPS - the returned object gets lost when the function is left...
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您也希望能够添加Reals,那么您将有另一种类型转换。不过,假设Integer + Real结果为Real,则您必须将返回类型改回Number

然而,其中包含一个很大的问题:函数一离开返回的对象就会被销毁,因此返回的引用是悬空的。

我们必须通过某种方式解决这个问题。但是,引用并不合适,因此我们可能会选择智能指针:

class Number
{
    virtual std::unique_ptr<Number> operator+(Number const&) const = 0;
};

class Integer : public Number
{
    std::unique_ptr<Number> operator+(Number const& other) const override
    //                 ^
    // unfortunately, now, as ordinary struct, no co-variance possible any more
    {
        return std::make_unique<Integer>(this->value + o->value);
    }
};
Run Code Online (Sandbox Code Playgroud)

这个问题再次说明了实际选择的方法是多么不合适......

  • 你在这里返回一个悬空引用。一种可能的解决方案是返回 `std::unique_ptr&lt;Number&gt;`。 (2认同)