关于派生中虚函数的问题
#include<iostream>
using namespace std;
class a
{
public:
virtual void display()
{cout<<"aaaa"<<endl;}
};
class b:public a
{
private:
void display()
{cout<<"bbbb"<<endl;}
};
int main()
{
a *p=new b;
p->display();
return 0;
}
指向a的指针指向b,该指针只能指向b中基类部分。但由于display()是基类的虚函数,在调用该函数时,该函数在派生类中重新定义,指针也能调用该函数。到这里为此都是我个人的理解。但问题是display()在派生类中是私有属性的,指针为什么能调用该函数呢?求高人解答!
类 指针
[解决办法]
编译器没有保存权限信息, 运行的时候是不会去检查权限的. 找到了函数指针就调就是了.
权限检查只会发生在编译的时候, 而编译的时候, 你是通过 a 调用的, 是合法的.
[解决办法]
在override基类虚函数的时候,降低该虚函数的可见性是没有意义的,因为调用代码可以通过基类去调用。
通常这里编译器会给个警告。
[解决办法]
多态仅与行为有关,而与可访问性与可见性无关,只要a的virtual display()是public的,其子类的virtual display是否public没有关系:
11.6 Access to virtual functions [class.access.virt]
1 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.
[Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f()
{
D d;
B* pb = &d;
D* pd = &d;
pb->f(); //OK: B::f() is public,
// D::f() is invoked
pd->f(); //error: D::f() is private
}
—end example] 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 (B* in the example above).
甚至不可见也无所谓:
struct B {
virtual void f();
};
struct D : B {
void f(int);
};
struct D2 : D {
void f();
};
虽然D中的f隐藏了B的f,而且D的f并不是virtual,但是并不妨碍D2的f是virtual。
