gpt4 book ai didi

c++ - 虚拟析构函数必须是公开的吗?

转载 作者:IT老高 更新时间:2023-10-28 22:18:49 24 4
gpt4 key购买 nike

我发现几乎每个虚拟析构函数的代码片段都将其作为公共(public)成员函数,如下所示:

class Base
{
public:
virtual ~Base()
{
cout << "~Base()" << endl;
}
};
class Derived : public Base
{
public:
~Derived()
{
cout << "~Derived()" << endl;
}
};

虚拟析构函数必须是公共(public)的还是在某些情况下非公共(public)的虚拟析构函数才有意义?

最佳答案

Do virtual destructors have to be public or are there situations where a non-public virtual destructor makes sense?

类(class)用马。如果您需要多态删除,则使用 public 虚拟析构函数,否则您的析构函数根本不需要是虚拟的。

关注 Herb's advice :

Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.

In brief, then, you're left with one of two situations. Either:

  1. You want to allow polymorphic deletion through a base pointer, in which case the destructor must be virtual and public; or
  2. You don't, in which case the destructor should be nonvirtual and protected, the latter to prevent the unwanted usage.

关于c++ - 虚拟析构函数必须是公开的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15520233/

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