c++中的继承和纯虚函数
inheritance and pure virtual function in c++
这个程序没有得到想要的输出。我得到的警告是:
- 类'shape'有虚拟方法'shape',但没有虚拟析构函数。类'square'有虚方法' shape ',但没有虚析构函数。 类'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 = ▭
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,在其前面添加一个虚值
相关文章:
- C++虚函数继承
- 名称隐藏对静态函数继承的实例使用
- C++ std::vector 中的虚拟析构函数继承
- 具有相同名称的类的构造函数继承
- 多复制构造函数继承中的惊人行为
- CRTP 和复制/移动赋值/构造函数继承
- 复制构造函数继承动态分配的数组
- 谷神星求解器成本函数继承错误:模板可能不是虚拟的
- 无法从 c++ 中的构造函数继承
- 在构造函数继承中使用默认构造函数
- 如何定义从虚拟函数继承的静态函数
- 调用超类函数继承 c++
- 构造函数继承和直接成员初始化
- c++ 不明确的双非虚函数继承
- C++ - 使用私有参数的构造函数继承
- 通过可变参数模板进行C++11构造函数继承
- 使用模板进行函数继承
- C++11构造函数继承和不带参数的构造函数
- 函数继承问题
- C++11 - 构造函数继承