C ++:覆盖另一个方法调用的受保护方法 [英] C++: Overriding a protected method which is called by another method

查看:77
本文介绍了C ++:覆盖另一个方法调用的受保护方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆