没有operator =匹配这些操作数

时间:2015-12-06 17:27:36

标签: c++

我有一个名为Shape的抽象类,我正在尝试存储两个Rectangle个对象。但是,当我尝试将Rectangle分配给Shape对象时,编译器会向我标记有关赋值运算符的错误。

我很困惑为什么会出错

void createTwoRectangles(Shape* shape, int size) {
    Rectangle* r1 = nullptr;
    Rectangle* r2 = nullptr;

    shape[0] = createRectangle(&r1);
    shape[1] = createRectangle(&r2);
}

但这很好

void createTwoRectangles(Shape* shape, int size) {
    Rectangle* r1 = nullptr;
    Rectangle* r2 = nullptr;

    createRectangle(&r1);
    createRectangle(&r2);

    shape[0] = *r1;
    shape[1] = *r2;
}

如果我错了,请纠正我,但我还在指定一个矩形物体?为什么编译器说没有运算符在第一个函数上匹配这些操作数,但在第二个函数中没有?

以下是=

的重载Rectangle运算符
Rectangle& Rectangle::operator=(const Rectangle& rectangle) {
    if (this != &rectangle) {
        lowerLeft = rectangle.ll;
        upperRight = rectangle.ur;
    }

    return *this;
}

如果我重载了赋值运算符错误,我怎样才能正确地重载它以使用Shape对象?

编辑 - 这是我的createRectangle功能

Rectangle** createRectangle(Rectangle** rec) {
    Point* lowerPoint = nullptr;
    Point* upperPoint = nullptr;

    cout << "\n    Lower left point -\n";
    createAPoint(&lowerPoint);
    cout << "\n    Upper right point -\n";
    createAPoint(&upperPoint);

    while (*upperPoint < *lowerPoint) {
        cout << "\n    Error! Upper right point must be greater than lower left.\n";
        cout << "    Upper right point - \n";
        createAPoint(&upperPoint);
    }

    if (*rec)
        (*rec)->update(*upperPoint, *lowerPoint);
    else
        *rec = new Rectangle(*upperPoint, *lowerPoint);

    delete lowerPoint;
    delete upperPoint;

    return rec;
}

0 个答案:

没有答案