c++ - 'Circle::Area': 'override' 说明符在函数定义 Derektut 上非法
问题描述
我的问题实际上是两倍。我正在阅读本教程https://www.youtube.com/watch?v=6y0bp-mnYU0,在 1:07:45,他谈到了在定义抽象类的虚拟函数时使用 override 关键字。我将类声明和定义保存在不同的文件中。当我尝试在我的定义中使用覆盖时,它在 Visual Studio 2019 上的函数定义中给出了“'覆盖'说明符非法”。这是为什么?
包括“Circle.h” 包括“Shape.h”
double Circle::Area() override {
return 3.14159 * pow((width / 2), 2);
}
另外,这个代码片段有什么作用?我是 C++ 新手:
Circle::Circle(double width) : Shape(width) {
}
为什么圆形使用抽象类的构造函数?这甚至可能吗?: Shape(width) 有什么作用。
这是“形状”类的样子:
class Shape
{
protected: //means that inherited classes will be able to access as long as it is part of protected
double height;
double width;
public:
static int numofShapes;
Shape(double length);
Shape(double height, double width);
Shape();
Shape(const Shape& orig);
virtual ~Shape();
//Setters and getters for privat mems
void Setheight(double height);
double Getheight();
void Setwidth(double height);
double Getwidth();
static int Getnumofshapes();
virtual double Area() = 0; //makes it an abstract base class
//私有:只有类代码
解决方案
Circle::Circle(double width) : Shape(width) {
}
这段代码片段是Circle
. 后面的东西:
是初始化列表,用于初始化类的数据成员。
class A {
public:
A() : val1(1), val2(2) {
}
private:
int val1; // is initialized to 1
int val2; // is initialized to 2
}
在初始化列表中,您不仅要初始化字段,而且Shape
当基类没有默认构造函数(没有参数的构造函数)时,您还必须调用基类的构造函数(在这种情况下)。因此,作为初始值设定项列表中的第一个元素,您拥有基类的名称,括号中Shape
是构造函数的参数。
你会得到一个覆盖说明符非法的错误,因为你没有在基类 ( )中声明一个virtual
带有 -function 签名的函数。请参阅此stackoverflow 帖子以了解虚函数的工作原理以及它们的用途。Area
Shape
推荐阅读
- javascript - 如何在 JavaScript 中添加 CSS 类?
- javascript - 在角度模板中使用 jquery ui 小部件
- javascript - mongoDB 上整个集合的平均值
- javascript - 从离子警报将警报文本输入保存到数据库中
- c++ - 使用 qprocess 将参数传递给批处理
- powerbi-embedded - Power Bi Embedded Javascript api getVisuals
- mysql - 如何使用 ruby 和 mysql 创建可以在不同系统中运行的 docker 映像
- d3.js - D3.js v4 如何获取数据?
- html - 使用 justify-content 在 div 中定位按钮
- android - 如何在 Android 中对 LiveData 进行单元测试