作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么我的代码返回错误?我定义了一个名为Shape的父类和两个派生类。我正在尝试存储由类定义的对象,并将它们存储在列表中。
# include <iostream>
using namespace std;
class Shape{
public:
virtual double area(const double &height, const double &weight) const = 0;
};
class Triangle: public Shape{
public:
double height, weight;
Triangle(double height, double weight): height(height), weight(weight){}
double area(){
return (height*weight)/2;
}
};
class Rectangle: public Shape{
public:
double height, weight;
Rectangle(double height, double weight): height(height), weight(weight){}
double area(){
return height*weight;
}
};
Shape *shapes[3];
shapes[0] = new Triangle(2, 1);
shapes[1] = new Rectangle(3, 2);
shapes[2] = new Rectangle(5, 2);
double * show(Shape *shapes){
double arr[3];
for (int i=0; i < 3; i++){
arr[i] = shapes[i].area();
}
return arr;
}
int main(){
double arr[3] = show(shapes);
cout << arr[0] << endl;
cout << arr[1] << endl;
cout << arr[2] << endl;
}
error: 'shapes' does not name a type Shapes[0] = new Trangle(2,1);
error: cannot convert 'shape**' to 'shape*' double arr[3] = show(shapes);
最佳答案
您的代码有几个问题:
Shape
具有接受参数的纯虚函数area()
,但您的派生类则不接受。因此,它也使派生类成为abstract
,因此您无法初始化派生类对象。 Shapes* shapes[3];
的数组,然后在全局范围中单独分配它们。这是您遇到的第一个错误。更完整的说明,请参见here show(shapes)
函数时,shapes
是Shapes*
数组的名称,它衰减为指向第一个元素的指针。结果类型应为Shapes**
,这是您遇到的第二个错误。 shapes[i]
函数中的show()
是指向对象的指针,因此您应该使用->
而不是.
double arr[3];
是堆栈上的一个数组,因此函数完成并返回后,其内容将被删除。未将指针返回到已存储的元素是未定义的。 delete
创建的所有对象进行new
,导致内存泄漏。 # include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
class Triangle : public Shape {
public:
double height, weight;
Triangle(double height, double weight) : height(height), weight(weight) {}
double area() const override { //add override to let compiler check for correctness
return (height * weight) / 2;
}
};
class Rectangle : public Shape {
public:
double height, weight;
Rectangle(double height, double weight) : height(height), weight(weight) {}
double area()const override {
return height * weight;
}
};
Shape* shapes[3] = { new Triangle(2, 1), new Rectangle(3, 2) ,new Rectangle(5, 2) };
double* show(Shape** shapes) {
double* arr = new double[3];
for (int i = 0; i < 3; i++) {
arr[i] = shapes[i]->area();
delete shapes[i]; //free the object pointed in shapes[]
}
return arr;
}
int main() {
double* arr = show(shapes);
cout << arr[0] << endl;
cout << arr[1] << endl;
cout << arr[2] << endl;
delete[] arr;
}
new
而不是堆的情况下在堆栈上创建对象,以及使用
std::array
创建数组等。
关于c++ - 多态性并在C++中定义不同对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60014544/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!