【发布时间】:2020-02-01 06:18:59
【问题描述】:
为什么我的代码返回错误?我定义了一个名为 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;
}
但我收到这两个错误:
错误:“形状”没有命名类型 形状[0] = 新三角形(2,1);
错误:无法将 'shape**' 转换为 'shape*' 双 arr[3] = 显示(形状);
【问题讨论】:
-
shapes[0] = new Triangle(2, 1);等 - 您不能在全局范围内拥有代码。将这些语句移到main()中。 -
另外,
show()返回一个指向局部变量的指针。那是UB。 -
除了 Sid S 的回复,您的
Shape* shapes[3];定义了一个大小为 3 的Shape*类型的数组。数组的名称是指向第一个元素的指针(这里不讨论衰减),所以shapes的类型为Shape**。你的shapes[i].area()应该是shapes[i]->area()。您的纯虚函数area()未在派生类中正确覆盖。 -
@Sid S。我已经按照你说的做了,但我收到了这个错误:抽象类类型“三角形”的新表达式无效。
-
@szppeter - 对不起,那是错误的。数组的名称不是指针。数组的名称可以当在某些上下文中使用它是指针,在某些上下文中隐式转换为指针(有些人称之为“衰减”),但它不是指针.当然,
Shape *数组和Shape **数组完全不同。
标签: c++