C ++:覆盖另一个方法调用的受保护方法 [英] C++: Overriding a protected method which is called by another method
问题描述
关于C ++中的继承,我有一个非常基本的问题:
I have a very basic question concerning inheritance in C++:
class A
{
public:
void foo() { print(); }
protected:
void print() {}
};
class B : public A
{
protected:
void print() { std::cout << "test" << std:: endl; }
};
现在下面的代码
B b;
b.foo();
不打印任何内容,因此foo()显然没有调用新定义的print().这只能通过使用虚拟方法解决吗?
doesn't print anything, so foo() obviously didn't call the newly defined print(). Is this only solvable by using virtual methods?
推荐答案
是的,您需要将print
设为虚拟才能使其正常工作.否则,A::foo
不知道后代可以提供print
的替代实现,这是对A
的版本的愉快调用.在编译A
的代码时,编译器甚至可以在foo
内部插入print
,这使得在B
中的实现完全不相关.
Yes, you need to make print
virtual in order for this to work. Otherwise, A::foo
has no idea that descendants could provide alternative implementations of print
, an happily calls A
's version. Compiler may even inline the print
inside foo
at the time A
's code is compiled, making the implementation in B
completely irrelevant.
这篇关于C ++:覆盖另一个方法调用的受保护方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!