gpt4 book ai didi

c++ - 在 C++ 编译期间出现 'has virtual method ... but non-virtual destructor' 警告是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 12:30:33 30 4
gpt4 key购买 nike

#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

如何理解这个警告以及如何改进代码?

[EDIT] 这个版本现在正确吗? (试图给出答案以阐明自己的概念)

#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(){}
};

最佳答案

如果一个类有一个虚方法,这意味着你希望其他类继承它。这些类可以通过基类引用或指针来销毁,但这仅在基类具有虚拟析构函数时才有效。如果你有一个应该可以多态使用的类,那么它也应该可以多态删除。

这个问题也有深入解答here .下面是一个完整的示例程序,演示效果:

#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

注意 delete bar; 导致析构函数 ~Bar~BarBase 被调用,而 delete foo; 只调用 ~FooBase。后者甚至是undefined behavior ,所以不能保证效果。

关于c++ - 在 C++ 编译期间出现 'has virtual method ... but non-virtual destructor' 警告是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8764353/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com