C++ 保护成员继承
C++ protected member inheritance
我的问题是为什么我不能通过指向基 class 的指针在派生 class 中调用受保护的虚拟成员函数,除非将派生 class 声明为基 [=32] 的友元=]?
例如:
#include <iostream>
class A {
friend class C; // (1)
protected:
virtual void foo() const = 0;
};
class B : public A {
void foo() const override { std::cout << "B::foo" << std::endl; }
};
class C : public A {
friend void bar(const C &);
public:
C(A *aa) : a(aa) { }
private:
void foo() const override {
a->foo(); // (2) Compile Error if we comment out (1)
//this->foo(); // (3) Compile OK, but this is not virtual call, and will cause infinite recursion
std::cout << "C::foo" << std::endl;
}
A *a;
};
void bar(const C &c) {
c.foo();
}
int main() {
B b;
C c(&b);
bar(c);
return 0;
}
输出为
B::foo
C::foo
在上面的代码中,我想通过classC
的成员a
调用虚函数foo()
(不是通过[=15=的静态绑定) ] 在编译时),但是如果我不让 C
成为 A
的朋友,调用是非法的。
我认为C
是继承自A
,所以它可以访问A
的protected
成员,但为什么实际上没有呢?
Class C
可以访问其自己的基 class 的受保护成员,但不能访问任何其他 A
的成员。
在您的示例中,参数 a
是完全不相关的 class B
的一部分,C
没有访问权限(除非您将其设为好友).
我的问题是为什么我不能通过指向基 class 的指针在派生 class 中调用受保护的虚拟成员函数,除非将派生 class 声明为基 [=32] 的友元=]?
例如:
#include <iostream>
class A {
friend class C; // (1)
protected:
virtual void foo() const = 0;
};
class B : public A {
void foo() const override { std::cout << "B::foo" << std::endl; }
};
class C : public A {
friend void bar(const C &);
public:
C(A *aa) : a(aa) { }
private:
void foo() const override {
a->foo(); // (2) Compile Error if we comment out (1)
//this->foo(); // (3) Compile OK, but this is not virtual call, and will cause infinite recursion
std::cout << "C::foo" << std::endl;
}
A *a;
};
void bar(const C &c) {
c.foo();
}
int main() {
B b;
C c(&b);
bar(c);
return 0;
}
输出为
B::foo
C::foo
在上面的代码中,我想通过classC
的成员a
调用虚函数foo()
(不是通过[=15=的静态绑定) ] 在编译时),但是如果我不让 C
成为 A
的朋友,调用是非法的。
我认为C
是继承自A
,所以它可以访问A
的protected
成员,但为什么实际上没有呢?
Class C
可以访问其自己的基 class 的受保护成员,但不能访问任何其他 A
的成员。
在您的示例中,参数 a
是完全不相关的 class B
的一部分,C
没有访问权限(除非您将其设为好友).