【问题标题】:'Circle::Area': 'override' specifier illegal on function definition Derektut'Circle::Area': 'override' 说明符在函数定义 Derektut 上非法
【发布时间】:2020-04-26 05:28:13
【问题描述】:

我的问题实际上是两个方面。我正在阅读本教程https://www.youtube.com/watch?v=6y0bp-mnYU0,在 1:07:45,他谈到了在定义抽象类的虚拟函数时使用 override 关键字。我将类声明和定义保存在不同的文件中。 当我尝试在我的定义中使用 override 时,它​​在 Visual Studio 2019 上的函数定义中给了我“'override' 说明符非法”。这是为什么?

包括“Circle.h” 包括“Shape.h”

double Circle::Area() override {    
    return 3.14159 * pow((width / 2), 2);
}

另外,这段代码 sn-p 有什么作用?我是 C++ 新手:

Circle::Circle(double width) : Shape(width) {

}  

为什么 circle 使用抽象类的构造函数?这甚至可能吗? : Shape(width) 有什么作用。

这是“Shape”类的样子:

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

//私有:只有类代码

【问题讨论】:

  • 如果由于定义在声明之外而不需要覆盖,编译器如何知道正确覆盖?
  • Shape 不是抽象的(它没有任何纯虚函数),它也没有 virtual double Area() 函数你可以 override

标签: c++


【解决方案1】:
Circle::Circle(double width) : Shape(width) {

}  

这段代码sn-p是Circle的构造函数的实现。 : 后面的东西是初始化列表,用于初始化你的类的数据成员。

class A {
    public:
        A() : val1(1), val2(2) {

        }

    private:
        int val1;    // is initialized to 1
        int val2;    // is initialized to 2
}

在初始化列表中,你不仅要初始化字段,而且当基类没有默认构造函数(constructor没有参数)。因此,作为初始化列表中的第一个元素,您拥有基类的名称,括号中是Shape 的构造函数的参数。


您会收到一个错误,即覆盖说明符非法,因为您没有在基类 (Shape) 中声明带有 Area 函数签名的 virtual 函数。请参阅thisstackoverflow 帖子,了解虚函数的工作原理以及它们的用途。

【讨论】:

  • 但我在 Shape 类中调用了虚拟区域:虚拟双区域()=0。
  • 我已经编辑了我的原始问题以包含其他功能。您现在将看到设计的 Area() 是纯虚函数。此外,Shape 类确实有一个默认构造函数。它在原始问题中。那么我有一个默认构造函数,为什么还要继承基类的构造函数呢?
  • 我已经编辑了我的原始问题以包含其他功能。您现在将看到设计的 Area() 是纯虚函数。此外,Shape 类确实有一个默认构造函数。它在原始问题中。所以我有一个默认构造函数,为什么还要继承基类的构造函数@DasElias
猜你喜欢
  • 2011-02-26
  • 2017-06-08
  • 2014-01-17
  • 1970-01-01
  • 2019-04-17
  • 2016-12-04
  • 2012-03-14
  • 2015-01-21
  • 2015-06-28
相关资源
最近更新 更多