首页 > 解决方案 > '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

//私有:只有类代码

标签: c++

解决方案


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 帖子以了解虚函数的工作原理以及它们的用途。AreaShape


推荐阅读