简体   繁体   English

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

[英]Overloaded function in derived class with Polymorphism (C++)

Considering this code example:考虑这个代码示例:

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

I wanted to use polymorphism and call theoverloaded print() function.我想使用多态并调用重载的print()函数。
So use these classes as follows:所以使用这些类如下:

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
}

Unfortunately, I can't call print() from the base class pointer (compilation error, see comment above).不幸的是,我无法从基类指针调用 print()(编译错误,请参阅上面的注释)。 I can only call it with a cast.我只能用演员表来称呼它。 Is there a better way to keep the polymorphism and still calls overloaded function based on derived class?有没有更好的方法来保持多态性并且仍然基于派生类调用重载函数?

In your code you have two different member functions, that have different signatures:在您的代码中,您有两个不同的成员函数,它们具有不同的签名:

  • a virtual print() that takes no argument.一个不带参数的虚拟print() It is declared and defined in Base , and inherited in Derived它在Base声明和定义,并在Derived继承
  • a non-virtual print() that takes one int argument.一个接受一个int参数的非虚拟print() It is declared and defined ONLY for Derived它仅针对Derived声明和定义

So the base object doesn't know a print function with an int parameter.所以基础对象不知道带有 int 参数的打印函数。 This is why you need to cast (which is by the way a symptom that should ring alarm bells if you need it).这就是为什么你需要施放(顺便说一句,如果你需要的话,这是一种应该敲响警钟的症状)。

How to improve ?怎么提高 ?

First, if you want to override a virtual function in a derived class, use the keyword override :首先,如果要覆盖派生类中的虚函数,请使用关键字override

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

This will ensure an error message in case of subtle mismatch in the function signature:这将确保在函数签名中出现细微不匹配时出现错误消息:

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

Then make sure that the signatures are aligned in the base class and derived class (ie either both take an int argument or non of them.然后确保签名在基类和派生类中对齐(即两者都采用 int 参数或不采用它们。

Note that you can't access a private member of the base class in a derived class.请注意,您不能在派生类中访问基类的private成员。 You have to define number as protected to print it in Derived .您必须将number定义为protected才能在Derived打印它。

Finally, if you have a base class having a virtual member, it is a sound practice to systematically make the destructor virtual.最后,如果您有一个具有虚拟成员的基类,那么系统地使析构函数成为虚拟成员是一个合理的做法。 This will avoid subtle bugs for more complex classes:这将避免更复杂的类的细微错误:

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

Here the online demo这里是在线演示

Now that the things are working, here a short article making the difference between overload and override .现在一切正常,这里有一篇简短的文章介绍了重载覆盖之间区别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 派生类中的重载函数 (C++) - Overloaded function in derived class (C++) C ++静态多态性–引用专业模板方法,这些方法从基类指针的派生类中重载 - C++ Static Polymorphism––Referencing Specialized Template Methods Overloaded In Derived Class From Base Class Pointer C ++派生类重载函数(带有std :: function参数)不可见 - C++ derived class overloaded function (with std::function argument) not visible 如何从派生类中调用在派生类中重载的模板类函数? - c++ How do you call a template class function that is overloaded in the derived class, from the derived class? c ++多态,派生类的名称解析 - c++ polymorphism, name resolution for derived class 从基对象上的 C++ 类调用重载的派生函数不会调用重载函数 - Call overloaded, derived function from C++ class on base object does not call the overloaded function 派生类中的C ++重载方法 - c++ overloaded method in derived class C ++多态性:如果派生类中的虚函数在基类中声明为常量,是否需要将其声明为常量 - C++ Polymorphism: Does a virtual function in derived class needs to be declared constant if its declared constant in base class C++ 多态性:是否可以将 function 从双派生 class 使用到基础 ZA2F2ED4F8EBC2ABC1DZC20? - C++ Polymorphism : Is it possible to use a function from a double derived class into the base class? 当在C ++中获得指向基类的指针时,为什么不为派生类对象调用重载函数? - Why is not overloaded function for derived class object invoked when given a pointer to base class in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM