带有多态性的派生类中的重载函数(C ++)

时间:2017-09-27 21:31:59

标签: c++ class polymorphism overloading virtual

考虑这个代码示例:

#include <iostream>
using namespace std;

class Base
{
private:
    int number;

public:
    Base():number(10){}
    ~Base(){}
    virtual void print()
    {
        cout << "Base class" << endl;
    }
};

class Derived : public Base
{
public:
    Derived():Base(){}
    ~Derived(){}
    void print(int value)
    {
        //printing number in Base class and paramter value
        cout << "Derived with value " << value << " number is" << number << endl; 
    }
};

我想使用多态并调用过载的print()函数 所以使用这些类如下:

void somewhere_else()
{
    Base* polymorphism = new Derived();
    polymorphism->print(5); //Error indicating there are too many parameter
                            //thinking that I am trying to use print in Base class
    ((Derived*)polymorphism)->print(5) 
                       //This works as I am casting the variable as Derived variable
}

不幸的是,我无法从基类指针调用print()(编译错误,请参阅上面的注释)。我只能用演员来称呼它。 是否有更好的方法来保持多态性并仍然基于派生类调用重载函数?

1 个答案:

答案 0 :(得分:1)

在您的代码中,您有两个不同的成员函数,它们具有不同的签名:

  • 不带参数的虚拟print()。它在Base中声明和定义,并在Derived
  • 中继承
  • 一个非虚拟print(),它带有一个int参数。它仅为Derived
  • 声明和定义

因此基础对象不知道带有int参数的打印函数。这就是你需要施放的原因(顺便提一下,如果你需要它就会响起警报铃声)。

如何改进?

首先,如果您想在派生类中覆盖虚拟函数,请使用关键字override

class Derived : public Base
{
public:
    Derived():Base(){}
    ~Derived(){}
    void print(int value) override
    {
        ...
    }
};

这将确保在函数签名中出现细微不匹配的情况下出现错误消息:

prog.cpp:23:10: error: ‘void Derived::print(int)’ marked ‘override’, but does not override
     void print(int value) override
          ^~~~~

然后确保签名在基类和派生类中对齐(即两者都采用int参数或非参数。

请注意,您无法在派生类中访问基类的private成员。您必须将number定义为protected才能在Derived中打印出来。

最后,如果你有一个具有虚拟成员的基类,那么系统地使析构函数成为虚拟是一种合理的做法。这将避免更复杂的类的微妙错误:

class Base
{
protected:
    int number;   
public:
    Base():number(10){}
    virtual ~Base(){}
    virtual void print(int value)
    {
        ...
    }
};

这里是online demo

现在事情正在发挥作用,这是一篇简短的文章,内容是difference between overload and override

相关问题