2013-05-22 39 views
11

我有一个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++。

+0

您是否尝试将该声明放入.H文件中? – Shark

+3

@Shark:那会发生什么变化? – Mat

+1

虚拟Figabs运算符+()= 0不带参数 - >返回不同类型的点运算符+(const Coord&vector)?他们的签名必须是一样的... – Exceptyon

回答

9

正如其他海报指出的,这项任务远不是 微不足道,而operator+通常不是会员。有应提到的两个问题 :

  1. 如果你支持`FigAbs + Coord`,那么你也应该支持 `坐标+ FigAbs`。第一个可以是一个成员(那里没有真正的 问题);第二,如果它是成员,则必须是'Coord`的成员 ,这可能不是想要的。
  2. 任何合理执行`operator +`必须返回 的值。而且你不能(通常)返回 值的多态类。你需要的东西像字母信封成语 这个工作:基类必须像:
     
    class Figure : BinaryOperators<Figure, Coord> 
    { 
        Figure* myImpl; 
    public: 
        Figure& operator+=(Coord const& translation) 
        { 
         myImpl->operator+=(translation); 
         return *this; 
        } 
    }; 
    
    当然,你所需要的正确 实例`Figure`每个不同类型的工厂方法,一虚拟 `clone`函数,以及复制构造函数,赋值和支持深度复制的析构函数。 (`BinaryOperators`是 它实现`操作者+`在 `操作者而言+ =`模板类;这是通常的方式,以提供二进制 运营商)

最后,我认为,这是运营商超载滥用。 加法的概念不适用于几何图形。 你在做什么叫做翻译,而逻辑 解决方案是提供一个成员函数,而不是 超载。

3

Figabs包含纯虚成员函数virtual Figabs operator +()=0;这意味着你不能实例Figabs

考虑:

virtual Figabs& operator +()=0; 
/*Now you will not be returning an actual instance but can return derived class instances* 
+7

返回值的位置是指什么? – BoBTFish

+0

谢谢,这使得错误消失了,但现在派生类,我有:Puncte运算符+(const Coord&vector)说错误:返回类型不完全相同,也不与协变类型返回类型Figabs&overridden虚函数Figab: :运营商+ – Casandra

+0

@BoBTFish我完全看到并同意。这是一个非常具体的答案,提请注意编译器错误的原因,而不是完整的解决方案。 – DuncanACoulter