多态性(C )的派生类中的超载函数

Overloaded function in derived class with Polymorphism (C++)

本文关键字:超载 函数 派生 多态性      更新时间:2023-10-16

考虑此代码示例:

#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; 
    }
};

我想使用多态性并调用theoverpoladed 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()(编译错误,请参见上面的注释)。我只能用演员来称呼它。有没有更好的方法来保持多态性,并且仍会根据派生类调用重载函数?

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

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

因此,基本对象不知道具有int参数的打印函数。这就是为什么您需要施放的原因(顺便说一句,如果您需要的话,应该响起警报铃的症状)。

如何改进?

首先,如果要 Override 派生类中的虚拟函数,请使用关键字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中打印。

最后,如果您有一个虚拟成员的基类,则系统地使destuructor虚拟化是一种合理的做法。这将避免更复杂的类的细微错误:

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

在这里,在线演示

现在事物正在正常工作,这里有一篇简短的文章,在 Overload Override 中有所不同。