问题描述
所以我正在修改继承和抽象类。在我正在编程的实例中,我创建了一个指向 Shape(我的抽象基类)的指针数组。在用 Square 子类指针填充数组中的前 2 个点后,我用前两个的总和填充第三个点。这给了我一个“表达式必须具有整数或无作用域枚举类型”错误,这给我带来了一些麻烦。此外,它给了我错误“'+'不能添加两个指针。”
#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;
}
有什么想法吗?
解决方法
无法尝试编译您的代码,因为类定义不可用。 乍一看,这行代码看起来不正确。
shapes[2] = shapes[0] + shapes[1];
shapes[2]
是一个指向 shape 的指针,但您还没有为该堆索引创建 shape
的实例。所以这样的事情可能会解决你的问题,但是我再次无法测试这个,因为原始帖子中没有类定义
shapes[2] = new Square();
*shapes[2] = *shapes[0] + *shapes[1];
关于当您简单地将第三个索引设置为等于第二个索引时您的实现工作;这可能有效,因为听起来您正在将第三个索引设置为指向您的第二个索引所指向的同一地址。如果是这样,那是有效的,因为它们只是地址