gpt4 book ai didi

c++ - 我可以禁止从基类调用派生类的私有(private)成员吗?

转载 作者:行者123 更新时间:2023-12-03 07:09:12 25 4
gpt4 key购买 nike

我有这个代码:

struct A {
virtual void f() {}
};
struct B: A {
private:
void f() override {}
};
...
B b;
A& a = b;
a.f();
当然它会调用 f()来自 B因为在编译时检查了私有(private),但在运行时选择了虚拟功能版本。我可以禁止 f()在这种情况下打电话?

最佳答案

没有。正如您调用 f()A引用,访问规则检查A .你不能指望编译器检查 B 的规则。 , 因为它不一定知道 aB 类型.
来自 cppreference :

Access rules for the names of virtual functions are checked at the call point using the type of the expression used to denote the object for which the member function is called. The access of the final overrider is ignored:

struct B { virtual int f(); }; // f is public in B

class D : public B { private: int f(); }; // f is private in D

void f() {
D d;
B& b = d;
b.f(); // OK: B::f is public, D::f is invoked even though it's private
d.f(); // error: D::f is private
}
不过,您的代码不应依赖于此。在我看来,给定方法的访问说明符应该在整个类层次结构中保持一致。

关于c++ - 我可以禁止从基类调用派生类的私有(private)成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65001923/

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