gpt4 book ai didi

c++ - 为什么 C++ 允许对公共(public)继承基方法进行访问限制?

转载 作者:可可西里 更新时间:2023-11-01 16:40:12 24 4
gpt4 key购买 nike

关于问题“How to publicly inherit from a base class but make some of public methods from the base class private in the derived class?”,我有一个后续问题:

我能理解 C++ 标准允许派生类放宽继承方法的访问限制,但我想不出任何合法的用例,在其中强加访问限制是有意义的派生类。

以我对继承概念的理解,如果类Derived是public class Base,那么你能用Base做的任何事情用Derived也能做。如果不想让 Derived 实现 Base 的接口(interface),那么一开始就不应该使用(公共(public))继承。 (事实上​​ ,当我在 ROOT 的 TH2::Fill(double) 中遇到这种技术时,这是一个明显的继承滥用案例。)

对于虚拟方法,Derived 中的访问限制也是无用的,因为 Derived 的任何用户都可以通过将 Derived* 转换为 Base* 来使用它们。

因此,从我有限的 C++ 新手的角度来看,这些限制具有误导性(Derived 的程序员可能会假设他现在 protected 虚拟方法未被任何其他人调用,而实际上它可能被调用)并且还会混淆 [我关于]公共(public)继承应该意味着什么。

我是否遗漏了一些合法的用例?

最佳答案

来自 Herb Sutter,Guru of the Week #18 :

Guideline #3: Only if derived classes need to invoke the base implementation of a virtual function, make the virtual function protected.

详细答案请看我在下面代码中的评论:

#include <iostream>
#include <typeinfo>
#include <memory>

struct Ultimate_base {
virtual ~Ultimate_base() {}
void foo() { do_foo(); }
protected:
// Make this method protected, so the derived class of this class
// can invoke this implementation
virtual void do_foo() { std::cout << "Ultimate_base::foo"; }
};

struct Our_derived : Ultimate_base {
private:
// Make this method private, so the derived class of this class
// can't invoke this implementation
void do_foo() {
Ultimate_base::do_foo();
std::cout << " Our_derived::foo";
}
};

struct Derive_from_derive : Our_derived {
private:
void do_foo() {
// You can't call below code
// vvvvvvvvvvvvvvvvvvvvvv
// Our_derived::do_foo();
std::cout << " Derive_from_derive::foo";
}
};

// This class is marked final by making its destructor private
// of course, from C++11, you have new keyword final
struct Derive_with_private_dtor : Ultimate_base {
private:
~Derive_with_private_dtor() {}
};

// You can't have below class because its destructor needs to invoke
// its direct base class destructor
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
/*
struct Derive_from_private_dtor : Derive_with_private_dtor {
};
*/

int main() {
std::unique_ptr<Ultimate_base> p = std::make_unique<Our_derived>();
p->foo();
p = std::make_unique<Derive_from_derive>();
p->foo();
p.reset(new Derive_with_private_dtor);
}

关于c++ - 为什么 C++ 允许对公共(public)继承基方法进行访问限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40406537/

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