【发布时间】:2013-05-22 10:42:05
【问题描述】:
我有一个 C++ 学校项目,但我被困在一个部分: 我必须重载运算符 + 和 * 才能处理几何图形。那没问题,但在这里它不起作用:我必须将运算符声明为纯虚方法,在所有其他类派生的抽象类中。
#include<iostream>
using namespace std;
class Figabs {
protected:
int fel;
public:
int getFEL() { return fel; }
virtual Figabs operator +()=0; /*this is where I get an error: function returning abstract class “Figabs” is not allowed : function Figabs::operator+ is a pure virtual function */
};
class Coord {
public:
int cx, cy;
public:
Coord (){
cx = cy = 0;
}
Coord (const int x, const int y) {
cx = x;
cy = y;
}
Coord (const Coord &din) {
cx = din.cx;
cy = din.cy;
}
~Coord () { }
void setX(const int val) { cx = val; } ;
void setY(const int val) { cy = val; };
int getX() { return cx; }
int getY() { return cy; }
};
class Point : public Coord, public Figabs { //one of the figures
public:
Point() {
setX(0);
setY(0);
fel = 0;
}
Point(const int x, const int y): Coord (x,y) {
fel = 0;
}
Point(const Point &din): Coord (din) {
fel = din.fel;
}
~Point() { }
Point operator +(const Coord &vector) { /*this works perfectly when I delete the declaration from the abstract class Figabs, but I don’t know how to make them work together */
int xp = cx + vector.cx;
int yp = cy + vector.cy;
return (Point (xp, yp));
}
Point operator *(const Coord &vector) {
Point temp;
temp.cx = cx * vector.cx;
temp.cy = cy * vector.cy;
return (temp);
}
};
谢谢你,请耐心等待,这是我第一次接触 C++。
【问题讨论】:
-
@Shark:那到底会发生什么变化?
-
virtual Figabs operator +()=0 with no arguments -> Point operator +(const Coord &vector) 返回不同的类型?他们的签名必须相同...
-
在没有 RHS 的操作员摘要的情况下,我仍在努力理解您的期望? (或者我错过了什么)?即使您确实提供了适当的操作,您的 retval 也会切片,顺便说一句。对于第一次 C++ 问题,您遇到了 很多 微妙的问题,所以对此表示欢迎 =P
-
这是一个有点棘手的问题,因为
operator+应该返回一个对象(不是引用),所以它不能返回一个抽象类(Figabs在这里是因为它有一个纯虚函数)。这在分配的约束下很难解决,至少部分原因是分配执行了糟糕的设计。operator+通常不应是成员函数(GOTW #4, part 5)。 -
@BoBTFish 解决起来很棘手,因为二元运算符的重载必须按值返回,而按值返回和多态不能很好地协同工作。完全没有。
标签: c++ operator-overloading pure-virtual