纯虚函数的过载 [英] Overload of pure virtual function

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

问题描述

我通常使用纯虚函数为那些方法,我的代码需要运行良好。因此,我创建接口,然后其他用户实现他们的派生类。派生类只有这些虚函数作为public,而一些额外的方法应该实现为私有,因为我的代码不调用它们。
我不知道这是否可以被认为是一个良好的实践OOP(有没有任何设计模式?)。
无论如何,我的问题是:
用户可以重载纯虚拟函数?



ie

  class Base 
{
public:
Base();
virtual〜Base();
virtual void foo(int,double)= 0;
};

class Derived:
public Base
{
private:
//方法
public:
Derived
virtual〜Derived();
virtual void foo(int,double,double) // this does not work
};

解决方案可以是:

  virtual void foo(int,double,double = 0)= 0; 

在基类中,但是它非常有限。你有什么想法?

解决方案

这两个函数不同。后者不覆盖第一个

  virtual void foo(int,double)= 0; 
virtual void foo(int,double,double);

第二个是特定于导出的新虚拟函数。



如果你在一个 override 在编译将抱怨你没有覆盖任何东西。这是c ++ 11检查。

  virtual void foo(int,double, 

用户可以覆盖纯虚函数以确认使用 override 在函数的结尾验证。 在您的情况下,第二个函数只能使用Derived指针或类型访问。(虽然它不能实例化,除非纯虚函数被正确覆盖和实现,直到它是一个抽象类)。因此,如果不打算通过派生自 Derived 的类进一步覆盖,那么使其成为虚拟是一种开销,无论如何它不会覆盖基本方法。 p>

I usually use pure virtual functions for those methods that are required by my code to work well. Therefore, I create interfaces and then other users implement their derived classes. The derived classes have only these virtual functions as public while some additional methods should be implemented as private since my code does not call them. I don't know if this can be considered as a good practice of OOP (are there any design pattern?). Anyway, my question is: Can a user overload a pure virtual function?

i.e.

class Base
{
public:
 Base();
 virtual ~Base();
 virtual void foo(int,double)=0;
};

class Derived:
public Base
{
 private:
  // methods
 public:
 Derived();
 virtual ~Derived();
 virtual void foo(int, double, double); //this doesn't work
 };

A solution could be:

 virtual void foo(int,double,double=0)=0;

in the base class but it is very limited. What do you think about?

解决方案

These 2 functions are different. The latter is not overriding the first

virtual void foo(int,double)=0;
virtual void foo(int, double, double);

The second one is new virtual function specific to derived.

If you put a override at the end the compile will complain that you are not overriding anything. This is c++11 check though.

virtual void foo(int, double, double) override;

The user can override a pure virtual function to confirm use override at the end of function to verify. In your case the second function can only be accessed using Derived pointer or type. (although it cannot be instantiated unless the pure virtual function is properly overridden and implemented, untill then it is an abstract class). Hence if it is not to be intended to be overidden further by classes that derives from Derived then making it virtual is a overhead as anyway it is not overidding the base method.

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

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