c++ - 将子对象复制到父对象
问题描述
我有三个类Shape
:Rectangle
和Circle
。Shape
是另外两个班级的父母。此类的定义在以下代码中:
#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;
}
我想要计算具有正确功能的所有形状的区域。我怎样才能做到这一点?
提前致谢
解决方案
要扩展 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
.
将派生类分配给基类的对象称为“对象切片”,通常会导致不良结果。使用指针(或引用)可以避免这种情况。
推荐阅读
- sql - IntelliJ 数据库:如何仅将更改的表行导出到更新 SQL 脚本?
- google-tag-manager - 我可以将服务器端事件发送到 Google Tag Manger
- python - 如何迭代存储的元素?(我不知道如何表达这个..)
- java - java.text.ParseException:无法解析的日期:android 中的“10/10/19 10:02”
- python - 如何执行这样的 pandas 聚合:删除 nan 并连接到第一个?
- javascript - Ajax 返回状态 200 但执行错误回调:如何从服务器捕获消息以编码为 json?
- azure-sqldw - CREATE EXTERNAL TABLE AS SELECT 语句失败
- angular - 类型 LeadPage(Module) 是 2 个模块声明的一部分
- pelican - 无法修改默认(简单)主题
- javascript - 从节点排序字母数字 li