多态性(C )的派生类中的超载函数
Overloaded function in derived class with Polymorphism (C++)
考虑此代码示例:
#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 中有所不同。
相关文章:
- 为什么STD :: SPAN超载函数调用操作员索引
- 类型长的长度和未解决的超载函数类型的类型的操作数与二进制运算符
- 如果我具有调用其其他实例之一的超载函数,它是否被认为是递归功能
- C bool表达式作为函数参数调用错误的超载
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 构造函数超载以接受任何功能
- 超载函数既不按值,也不是通过参考来对象,而是将撤销的指针换成对象
- 是否可以确定函数的参数是否已签名或无符号,以实现可能性超载函数
- 错误:找不到匹配的超载函数
- 在模板结构中超载函数
- 将超载函数指针作为参数传递到过载模板功能
- C -STD ::向量没有超载函数的实例
- C - 编译器如何以参数为参数的过载函数在超载函数之间决定
- 确定是否有针对特定类型的参数定义的超载函数
- bind shared_ptr ::重置 - 找不到匹配的超载函数
- 编译器是否也将所有参数依赖类型实例化,即使超载函数的参数计数不匹配
- 多态性(C )的派生类中的超载函数
- 需要说明简单的C 程序中的编译误差,以演示超载函数
- 超载函数调用功能具有相同名称,但参数不同
- 有多少操作数可以超载函数呼叫操作员采用