c++ - 如何在抽象超类的子类中重载 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;
}
有任何想法吗?
解决方案
由于类定义不可用,无法尝试编译您的代码。乍一看,这行代码看起来不正确。
shapes[2] = shapes[0] + shapes[1];
shapes[2]
是一个指向形状的指针,但您shape
尚未从堆中创建该索引的实例。因此,这样的事情可能会解决您的问题,但是由于原始帖子中没有类定义,因此我再次无法对此进行测试
shapes[2] = new Square();
*shapes[2] = *shapes[0] + *shapes[1];
当您简单地将第三个索引设置为等于第二个索引时,您的实现工作;这可能有效,因为听起来您将第三个索引设置为指向与第二个索引指向的地址相同的地址。如果是这样,那是有效的,因为它们只是地址
推荐阅读
- python - 更改桌面屏幕方向
- excel - 在本地复制工作表数据是否比将单元格链接到外部文件更适合内存消耗
- spring - Curl Spring 复杂对象为空
- google-drive-api - Google Drive API:列出共享驱动器下的所有文件夹
- c# - 在 C++ 中将 .bmp 图像大小调整为 1280X720
- javascript - JsonResponse 和 HTTPResponse 有什么区别?
- python - DuckDuckGo 在使用 Python 请求时返回 418
- c# - Blazor Server Scoped 在刷新页面时再次初始化
- java - Jenkins - Maven 项目 - SonarQube 分析不稳定 - 错误:无法为 - java.lang.IllegalArgumentException 创建符号表:null
- laravel - 迁移:创建新表时列已存在错误