首页 > 解决方案 > 将子对象复制到父对象

问题描述

我有三个类ShapeRectangleCircleShape是另外两个班级的父母。此类的定义在以下代码中:

#include <iostream>

using namespace std;

class Shape {
public:
    Shape() {

    }

    ~Shape() {

    }

    void set(float BORDER, string COLOR) {
        border = BORDER;
        color = COLOR;
    }

    double computeArea() {
        return 0;
    }

private:
    float border;
    string color;
};

class Circle : public Shape {
public:
    Circle() {

    }

    ~Circle() {

    }

    void setRadius(float RADIUS) {
        radius = RADIUS;
    }

    double computeArea() {
        return 3.14 * radius * radius;
    }

private:
    float radius;
};


class Rectangle : public Shape {
public:
    Rectangle() {

    }

    ~Rectangle() {

    }

    void setWidth(float w) {
        width = w;
    }

    void setLength(float l) {
        length = l;
    }

    double computeArea() {
        return width * length;
    }

private:
    float width;
    float length;
};

Circle我从和Rectangle类构建两个对象。然后我将这两个对象复制到Shape类中。当我computeArea()按以下顺序运行函数时,我得到了0结果。

int main() {
    Circle c;
    c.setRadius(3);
    Rectangle r;
    r.setWidth(4);
    r.setLength(5);

    Shape sh[2];

    sh[0] = c;
    sh[1] = r;

    cout << sh[0].computeArea() << endl;
    cout << sh[1].computeArea();

    return 0;
}

我想要计算具有正确功能的所有形状的区域。我怎样才能做到这一点?

提前致谢

标签: c++oop

解决方案


要扩展 Fureeish 所说的内容,请将您的代码更改为:

int main() {
    Circle c;
    c.setRadius(3);
    Rectangle r;
    r.setWidth(4);
    r.setLength(5);

    Shape *sh[2];

    sh[0] = &c;
    sh[1] = &r;

    cout << sh[0]->computeArea() << endl;
    cout << sh[1]->computeArea();

    return 0;
}

并将computeArea(以及Shape的析构函数,以防您通过指向基类的指针销毁派生对象)声明为virtual.

将派生类分配给基类的对象称为“对象切片”,通常会导致不良结果。使用指针(或引用)可以避免这种情况。


推荐阅读