为什么我可以通过指向派生对象的基类指针访问派生的私有成员函数? [英] Why can I access a derived private member function via a base class pointer to a derived object?
问题描述
#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;
}
输出 bye
我没有如何实现这个问题。我理解你使用vtables和vtable的派生包含新的add()函数的地址。但add()是私人的,不应该编译器生成错误时,我试图访问它的类外?
I dont have a problem with how this is implemented. I understand you use vtables and the vtable of derived contains the address of the new add() function. But add() is private shouldn't compiler generate an error when I try to access it outside the class? Somehow it doesn't seem right.
推荐答案
add()
只有派生
中的私人,但您拥有的静态类型是 base *
访问限制 base
适用。
一般来说,你甚至不能知道在编译时什么动态类型的指针 base
将会,它可以eg根据用户输入更改。
add()
is only private in derived
, but the static type you have is base*
- thus the access restrictions of base
apply.
In general you can't even know at compile time what the dynamic type of a pointer to base
will be, it could e.g. change based on user input.
这是根据C ++ 03§11.6:
This is per C++03 §11.6:
虚函数的访问规则(第11节)由其声明决定,不受后面覆盖它的函数的规则影响。
[。 ..]在调用点使用用于表示成员函数称为[...]的对象的表达式类型检查访问。成员函数在其定义的类中的访问[...]通常是未知的。
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.
这篇关于为什么我可以通过指向派生对象的基类指针访问派生的私有成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!