首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有多态性的派生类中的重载函数(C++)

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

Stack Overflow用户
提问于 2017-09-28 05:31:59
回答 1查看 105关注 0票数 1

考虑这个代码示例:

代码语言:javascript
复制
#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()函数。

因此请按如下方式使用这些类:

代码语言:javascript
复制
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() (编译错误,参见上面的注释)。我只能用石膏来形容它。有没有更好的方法来保持多态性,并且仍然调用基于派生类的重载函数?

EN

回答 1

Stack Overflow用户

发布于 2017-09-29 14:44:56

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

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

声明和定义

因此,基对象不知道带有int参数的print函数。这就是为什么你需要强制转换(顺便说一句,这是一个症状,如果你需要的话,它应该敲响警钟)。

如何改进?

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

代码语言:javascript
复制
class Derived : public Base
{
public:
    Derived():Base(){}
    ~Derived(){}
    void print(int value) override
    {
        ...
    }
};

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

代码语言:javascript
复制
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中打印它。

最后,如果您有一个具有虚拟成员的基类,那么系统地将析构函数设为虚拟是一种合理的做法。这将避免更复杂的类出现细微的bug:

代码语言:javascript
复制
class Base
{
protected:
    int number;   
public:
    Base():number(10){}
    virtual ~Base(){}
    virtual void print(int value)
    {
        ...
    }
};

这里是online demo

现在一切都正常了,下面是一篇制作difference between and 的短文。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46457539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档