在 class 之外调用的私有函数成员
Private function member called outside of class
在下面的示例中,为什么 B::f()
被调用,即使它是私有的?
我知道这个事实:
使用用于表示为其调用成员函数的对象的表达式类型在调用点检查访问权限。
#include <iostream>
class A {
public:
virtual void f() { std::cout << "virtual_function"; }
};
class B : public A {
private:
void f() { std::cout << "private_function"; }
};
void C(A &g) { g.f(); }
int main() {
B b;
C(b);
}
在编译期间 C++ 编译器根据类型验证函数和方法的可访问性。在函数 C 中,变量 g 是类型 A(在代码编译期间检查),其中方法 f 声明为 public。
private
函数可以从基 class 覆盖 public
虚函数。事实上,在确定一个函数是否覆盖另一个函数时,可访问性是完全被忽略的,所以即使在
// Redundant private for clarity:
class A { private: virtual void foo(); };
class B : A { public: void foo(); };
B::foo
覆盖 A::foo
。
因为标准是这样说的:
[C++11: 11.5/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 ]
例子和你的一样,哈哈
在下面的示例中,为什么 B::f()
被调用,即使它是私有的?
我知道这个事实: 使用用于表示为其调用成员函数的对象的表达式类型在调用点检查访问权限。
#include <iostream>
class A {
public:
virtual void f() { std::cout << "virtual_function"; }
};
class B : public A {
private:
void f() { std::cout << "private_function"; }
};
void C(A &g) { g.f(); }
int main() {
B b;
C(b);
}
在编译期间 C++ 编译器根据类型验证函数和方法的可访问性。在函数 C 中,变量 g 是类型 A(在代码编译期间检查),其中方法 f 声明为 public。
private
函数可以从基 class 覆盖 public
虚函数。事实上,在确定一个函数是否覆盖另一个函数时,可访问性是完全被忽略的,所以即使在
// Redundant private for clarity:
class A { private: virtual void foo(); };
class B : A { public: void foo(); };
B::foo
覆盖 A::foo
。
因为标准是这样说的:
[C++11: 11.5/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 ]
例子和你的一样,哈哈