考虑这个代码示例:
#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() (编译错误,参见上面的注释)。我只能用石膏来形容它。有没有更好的方法来保持多态性,并且仍然调用基于派生类的重载函数?
发布于 2017-09-29 14:44:56
在您的代码中,有两个不同的成员函数,它们具有不同的签名:
print()。它在Base中声明和定义,并在接受一个int参数的Derivedprint()中继承。它仅为Derived声明和定义
因此,基对象不知道带有int参数的print函数。这就是为什么你需要强制转换(顺便说一句,这是一个症状,如果你需要的话,它应该敲响警钟)。
如何改进?
首先,如果要在派生类中覆盖虚函数,请使用关键字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中打印它。
最后,如果您有一个具有虚拟成员的基类,那么系统地将析构函数设为虚拟是一种合理的做法。这将避免更复杂的类出现细微的bug:
class Base
{
protected:
int number;
public:
Base():number(10){}
virtual ~Base(){}
virtual void print(int value)
{
...
}
};这里是online demo
现在一切都正常了,下面是一篇制作difference between and 的短文。
https://stackoverflow.com/questions/46457539
复制相似问题