纯虚拟运营商

Cas*_*dra 11 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);
    } 
};
Run Code Online (Sandbox Code Playgroud)

谢谢,请耐心等待,这是我第一次接触C++.

Jam*_*nze 9

正如其他海报所指出的那样,这项任务远非微不足道,operator+通常也不是成员.有两个问题需要解决:

  1. 如果你支持`FigAbs + Coord`,那么你也应该支持`Coord + FigAbs`.第一个可以是成员(那里没有真正的问题); 第二个,如果它是一个成员,必须是'Coord`的成员,这可能不是想要的.
  2. `operator +`的任何合理实现都必须按值返回.并且你不能(通常)按值返回多态类; 你需要像letter-envelope这样的东西才能工作:基类必须看起来像:
    class Figure : BinaryOperators<Figure, Coord>
    {
        Figure* myImpl;
    public:
        Figure& operator+=( Coord const& translation )
        {
            myImpl->operator+=( translation );
            return *this;
        }
    };
    
    当然,你需要工厂方法来为每个不同类型正确实例化`Figure`,虚拟`clone`函数,以及支持深拷贝的复制构造函数,赋值和析构函数.(`BinaryOperators`是一个模板类,它根据`operator + =`实现`operator +`;这是提供二元运算符的常用方法.)

最后,我认为这是运营商超载滥用.添加的概念不适用于几何图形.你正在做的是被称为翻译,逻辑解决方案是提供一个成员函数来做到这一点,而不是过度添加.