gpt4 book ai didi

c++ - 在类外调用的私有(private)函数成员

转载 作者:IT老高 更新时间:2023-10-28 22:24:21 26 4
gpt4 key购买 nike

在下面的例子中,为什么 B::f() 被调用,即使它是私有(private)的?

我知道这个事实:在调用点使用用于表示调用成员函数的对象的表达式类型检查访问。

#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++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 ]

这个例子和你的一样,哈哈。

关于c++ - 在类外调用的私有(private)函数成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28097578/

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