纯虚拟运营商

时间:2013-05-22 10:42:06

标签: c++ operator-overloading pure-virtual

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

3 个答案:

答案 0 :(得分:9)

正如其他海报所指出的,这项任务远非如此 琐碎的,operator+通常不是会员。那里有两个 应该解决的问题:

  1. 如果您支持`FigAbs + Coord`,那么您也应该支持 `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`是 一个模板类,它实现了`operator +` `操作者+ =`;这是提供二进制文件的常用方法 运营商。)
  3. 最后,我认为这是运营商超载滥用。 添加的概念不适用于几何图形。 你正在做的是所谓的翻译,而且是合乎逻辑的 解决方案是提供成员函数,而不是 超载。

答案 1 :(得分: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*

答案 2 :(得分:0)

请查看以下链接,了解与问题相关的有用信息位

overriding virtual function return type differs and is not covariant

virtual Figabs operator +() = 0;//Here ur not passing any i/p parameters

但是在派生类中传递参数

Point operator +(const Coord &vector)//here ur sending i/p parameter .