【发布时间】:2023-01-27 19:45:48
【问题描述】:
我正在尝试在 C++ 中练习 OOP,但我遇到了一个关于覆盖函数的问题。在我的 Shape2D 和 Shape3D 类中,我有在 Square 和 Sphere 类(分别为 ShowArea() 和 ShowVolume())中重新定义的虚函数。但是,当我重新定义函数并尝试运行 main 时,它会输出错误:
Shapes.cpp:88:14: error: 'void Square::ShowArea() const' marked 'override', but does not override
void ShowArea() const override{
Shapes.cpp:353:14: error: 'void Sphere::ShowVolume() const' marked 'override', but does not override
void ShowVolume() const override {
下面是来自 Shape2D、Square、Shape3D 和 Sphere 类的相关代码的 sn-p。
class Shape2D : virtual public Shape {
public:
virtual float Area() const = 0;
void ShowArea() const;
virtual string GetName2D() const = 0;
}
class Square: public Shape2D {
private:
float squareLen;
public:
// Constructors
Square() {
squareLen = 0;
}
Square(float len) {
squareLen = len;
}
string GetName2D() const override {
string res;
return res;
}
// Returns the area of the shape
float Area() const override {
return (squareLen * squareLen);
}
void ShowArea() const override{
cout << "Square Area: " << endl;
}
}
class Shape3D : virtual public Shape {
public:
virtual float Volume() const = 0;
void ShowVolume() const;
virtual string GetName3D() const = 0;
}
class Sphere: public Shape3D {
private:
Circle* SphereBase;
public:
Sphere() {
SphereBase = new Circle();
}
Sphere(float radius) {
SphereBase = new Circle(radius);
}
float Volume() const {
return (1.3333 * pi * pow(SphereBase->GetRadius(), 3));
}
void ShowVolume() const override {
}
当我在子类中重新定义函数并且函数在其原始定义中是虚拟的时,为什么会出现这种情况?它不适用于我的任何形状(我有 6 种形状,但在这篇文章中只包含 2 种)所以我不认为它是一个错字并且它在 2D 和 3D 形状上崩溃所以它不是那些特定类的问题。
【问题讨论】:
-
您需要为
showArea和showVolume添加virtual关键字,以便showArea和showVolume可以是虚拟成员函数。 -
“并且该功能在其原始定义中是虚拟的”-- 不,它不是(除非原始定义在看不见的
Shape类中)。打字错误?
标签: c++ oop inheritance multiple-inheritance virtual-inheritance