C ++:私有虚拟函数与纯虚函数 [英] C++: Private virtual functions vs. pure virtual functions

查看:240
本文介绍了C ++:私有虚拟函数与纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++中的私有虚拟方法

这个帖子(http://stackoverflow.com/questions/2170688/private-virtual-method-in-c),在基类中创建一个虚函数使得派生类能够覆盖它。但是,似乎事情停止了。

If I understood correctly from this post (http://stackoverflow.com/questions/2170688/private-virtual-method-in-c), making a virtual function in a base class makes the derived classes able to override it. But it seems things stop there.

但是如果基类虚函数是纯的,强制派生类实现该函数。因此,纯(公共)虚拟功能仅仅是接口。我可以看到一个好处。

But if the base class virtual function is pure, that forces the derived classes to implement the function. Hence, a pure (public) virtual function is merely an interface. I can see a benefit here.

另一方面,通过使一个基类虚函数private,只给派生类重写该函数的能力,但我看不到这个的好处。这就好像私人虚拟功能甚至不存在。派生类显然不知道虚函数在基类中的存在,因为它的私有,那么在继承或多态性方面声明一个基类private function virtual有什么好处吗?

On the other hand, by making a base class virtual function private, only gives the derived class the ability to override the function, but I see no benefit of this. It's as if that private virtual function is not even there. The derived class obviously does not know about the existence of that virtual function in base class because its private, so is there any benefit of declaring a base class private function virtual, in term of inheritance or polymorphism?

还有,基类是否会声明一个函数纯虚拟和私有?

Also, is there any situation where a base class would declare a function 'pure virtual' and 'private'?

谢谢。 p>

Thank you.

推荐答案

一个好处是实施模板方法模式

class Base {

 public :
  void doSomething() {
    doSomething1();
    doSomething2();
    doSomething3();
  }
 private:
   virtual void doSomething1()=0;
   virtual void doSomething2()=0;
   virtual void doSomething3()=0;
};


class Derived : public Base {
  private:
   virtual void doSomething1() { ... }
   virtual void doSomething2() { .... }
   virtual void doSomething3() { .... }
}

这允许派生类实现某个逻辑的每个部分,而基类决定如何将这些部分组合在一起。由于这些块本身没有意义,因此它们被声明为 private ,因此对客户端代码隐藏。

This allows the derived classes to implement each piece of a certain logic, while the base class determines how to put these pieces together. And since the pieces don't make sense by themselves, they are declared private and so hidden from client code.

这篇关于C ++:私有虚拟函数与纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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