gpt4 book ai didi

c++ - 派生类中 protected 成员函数地址不可访问

转载 作者:可可西里 更新时间:2023-11-01 16:38:09 26 4
gpt4 key购买 nike

#include <iostream>

class A {
protected:
void foo()
{}
};

class B : public A {
public:
void bar()
{
std::cout << (&A::foo) << std::endl;
}
};

int main()
{
B b;
b.bar();
}

这里我试图获取基类的 protected 成员函数的地址。我收到此错误。

main.cpp: In member function ‘void B::bar()’:
main.cpp:5: error: ‘void A::foo()’ is protected
main.cpp:13: error: within this context
make: *** [all] Error 1

将 foo 更改为公共(public)工程。打印 &B::foo 也可以。能否请您解释一下为什么我们无法获取基类的 protected 成员函数的地址?

最佳答案

B 被允许访问 A 的 protected 成员,只要访问是通过 B 类型的对象执行的。在您的示例中,您试图通过 A 访问 foo,在这种情况下,B 是否派生自 A< 无关紧要 或不。

来自 N3337,§11.4/1 [class.protected]

An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2) As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C. [Example:

 class B {
protected:
int i;
static int j;
};
class D1 : public B {
};
class D2 : public B {
friend void fr(B*,D1*,D2*);
void mem(B*,D1*);
};
// ...
void D2::mem(B* pb, D1* p1) {
// ...
int B::* pmi_B = &B::i; // ill-formed
int B::* pmi_B2 = &D2::i; // OK
// ...
}
// ...

—end example]

您的示例与 D2::mem 中的代码非常相似,它表明试图通过 B 而不是 形成指向 protected 成员的指针D2 格式错误。

关于c++ - 派生类中 protected 成员函数地址不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28622970/

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