在C ++编译过程中,“虚拟方法...但是非虚拟析构函数”警告是什么意思? [英] What does 'has virtual method ... but non-virtual destructor' warning mean during C++ compilation?

查看:419
本文介绍了在C ++编译过程中,“虚拟方法...但是非虚拟析构函数”警告是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    virtual int area ()
      { return (0); }
  };

class CRectangle: public CPolygon {
  public:
    int area () { return (width * height); }
  };

有汇编警告

Class '[C@1a9e0f7' has virtual method 'area' but non-virtual destructor

如何了解此警告以及如何改进代码?

How to understand this warning and how to improve the code?

此版本是否正确? (尝试给出答案以阐明自己的概念)

is this version correct now? (Trying to give answer to elucidate myself with the concept)

#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    virtual ~CPolygon(){};
    virtual int area ()
      { return (0); }
  };

class CRectangle: public CPolygon {
  public:
    int area () { return (width * height); }
    ~CRectangle(){}
  };


推荐答案

如果一个类有一个虚方法,希望其他类继承它。这些类可以通过基类引用或指针来销毁,但是这只有在基类具有虚拟析构函数的情况下才有效。

If a class has a virtual method, that means you want other classes to inherit from it. These classes could be destroyed through a base-class-reference or pointer, but this would only work if the base-class has a virtual destructor. If you have a class that is supposed to be usable polymorphically, it should also be deletable polymorphically.

这个问题也有深入的回答在这里。以下是一个演示效果的完整示例程序:

This question is also answered in depth here. The following is a complete example program that demonstrates the effect:

#include <iostream>

class FooBase {
public:
    ~FooBase() { std::cout << "Destructor of FooBase" << std::endl; }
};

class Foo : public FooBase {
public:
    ~Foo() { std::cout << "Destructor of Foo" << std::endl; }
};

class BarBase {
public:
    virtual ~BarBase() { std::cout << "Destructor of BarBase" << std::endl; }
};

class Bar : public BarBase {
public:
    ~Bar() { std::cout << "Destructor of Bar" << std::endl; }
};

int main() {
    FooBase * foo = new Foo;
    delete foo; // deletes only FooBase-part of Foo-object;

    BarBase * bar = new Bar;
    delete bar; // deletes complete object
}

输出:

Destructor of FooBase
Destructor of Bar
Destructor of BarBase

请注意,删除栏; 会导致析构函数〜Bar code>〜BarBase ,而 delete foo; 只调用〜FooBase 。后者甚至是未定义的行为,因此不能保证效果。

Note that delete bar; causes both destructors, ~Bar and ~BarBase, to be called, while delete foo; only calls ~FooBase. The latter is even undefined behavior, so that effect is not guaranteed.

这篇关于在C ++编译过程中,“虚拟方法...但是非虚拟析构函数”警告是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆