首页 > 解决方案 > 如何在抽象超类的子类中重载 operator+?

问题描述

所以我正在修改继承和抽象类。在我正在编程的实例中,我创建了一个指向我的抽象基类 Shape 的指针数组。在用 Square 子类指针填充数组中的前两个点后,我用前两个的总和填充第三个点。这给了我一个“表达式必须具有整数或非范围枚举类型”的错误,这给我带来了一些麻烦。此外,它给了我错误“'+' 不能添加两个指针。”

#include <iostream>
#include <cmath>
#include <string>
#include "Shape.h"
#include "Square.h"

using namespace std;

int main()
{
    Shape** shapes = new Shape*[3];
    shapes[0] = new Square(12);
    shapes[1] = new Square(4);
    shapes[2] = shapes[0] + shapes[1];

    delete[] shapes;
    return 0;
}

有趣的是,如果我将第三个索引设置为等于第二个索引,它就可以正常工作。

下面是我的 Square 运算符。

Square& Square::operator=(const Square& c1)
{
    if (this != &c1)
    {
        this->length_O = c1.GetLength();
        this->width_O = c1.GetWidth();
    }
    return *this;
}

Square& Square::operator+=(const Square& c1)
{
    if (this != &c1)
    {
        this->length_O = c1.GetLength();
        this->width_O = c1.GetWidth();
    }
    return *this;
}

const Square Square::operator+(const Square& c1) const
{
    return Square(*this) += c1;
}

有任何想法吗?

标签: c++pointersinheritanceoperator-overloadingenumerator

解决方案


由于类定义不可用,无法尝试编译您的代码。乍一看,这行代码看起来不正确。

shapes[2] = shapes[0] + shapes[1];

shapes[2]是一个指向形状的指针,但您shape尚未从堆中创建该索引的实例。因此,这样的事情可能会解决您的问题,但是由于原始帖子中没有类定义,因此我再次无法对此进行测试

shapes[2] = new Square();
*shapes[2] = *shapes[0] + *shapes[1];

当您简单地将第三个索引设置为等于第二个索引时,您的实现工作;这可能有效,因为听起来您将第三个索引设置为指向与第二个索引指向的地址相同的地址。如果是这样,那是有效的,因为它们只是地址


推荐阅读