gpt4 book ai didi

c++ - 为什么我可以通过指向派生对象的基类指针访问派生私有(private)成员函数?

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

#include<iostream>

using namespace std;
class base
{
public:
virtual void add() {
cout << "hi";
}
};

class derived : public base
{
private:
void add() {
cout << "bye";
}
};

int main()
{
base *ptr;
ptr = new derived;
ptr->add();
return 0;
}

输出是再见

我对如何实现没有问题。我了解您使用 vtables,并且 derived 的 vtable 包含新的 add() 函数的地址。但是 add() 是私有(private)的,当我尝试在类外访问它时,编译器不应该产生错误吗?不知怎的,这似乎不对。

最佳答案

add() 仅在 derived 中是私有(private)的,但您拥有的 静态类型base* -因此 base 的访问限制适用。
通常,您甚至无法在编译时知道指向 base 的指针的动态类型是什么,例如根据用户输入进行更改。

这是根据 C++03 §11.6:

The access rules (clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.
[...] Access is 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 member function in the class in which it was defined [...] is in general not known.

关于c++ - 为什么我可以通过指向派生对象的基类指针访问派生私有(private)成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3610936/

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