【发布时间】:2021-07-06 13:27:12
【问题描述】:
所以我正在修改继承和抽象类。在我正在编程的实例中,我创建了一个指向我的抽象基类 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;
}
有什么想法吗?
【问题讨论】:
-
if (this != &c1)-- 为什么在operator+=中进行这个测试?这个a += a;应该是完全有效的。 -
另外,它给了我错误“'+' 不能添加两个指针。” -- 解释这一行的作用:
shapes[2] = shapes[0] + shapes[1]; -
您的
operator+=看起来与您的operator=完全相同。这是故意的吗?
标签: c++ pointers inheritance operator-overloading enumerator