c++中的继承和纯虚函数

inheritance and pure virtual function in c++

本文关键字:函数 继承 c++      更新时间:2023-10-16

这个程序没有得到想要的输出。我得到的警告是:

  1. 类'shape'有虚拟方法'shape',但没有虚拟析构函数。类'square'有虚方法' shape ',但没有虚析构函数。
  2. 类'rectangle'有虚拟方法' shape ',但没有虚拟析构函数。

虽然程序正在编译没有任何错误,但我没有得到的答案必须是20和18。我也无法理解这些警告的含义。为什么答案没有显示在屏幕上?还有,如果我要通过构造函数来初始化长度和宽度的值,我该如何初始化呢?

#include <iostream>
using namespace std;
class shape {
    int length;
    int breadth;
public:
    int area;
    virtual int shap(int, int) = 0;
};
class square : public shape {
public:
    int shap(int length, int breadth) { return area = length * breadth; }
};
class rectangle : public shape {
public:
    int shap(int length, int breadth) { return area = length * breadth; }
};
int main() {
    shape* s;
    square sq;
    rectangle rect;
    s = &sq;
    s->shap(4, 5);
    s = &rect;
    s->shap(6, 3);
    return 0;
}

我没有得到这个程序想要的输出。这些警告我得到的是:

Class 'shape' has virtual method 'shap' but non-virtual destructor.
lass 'square' has virtual method 'shap' but non-virtual destructor.
Class 'rectangle' has virtual method 'shap' but non-virtual destructor.

要清除警告,就像警告所说的那样。

在各自的类中添加析构函数。

virtual ~shape();
virtual ~rectangle()
virtual ~square();

对于rectangle:: shape和square:: shape,在其前面添加一个虚值